Make a div max width of two values?

Consider the basic HTML below:

<body>
    Random HTML content
    <div class="container">
        <!--Some content loaded via ajax or the like -->
    </div>
    Other random HTML content
</body>

      

I want the width of the "container" div to be the MAXIMUM of 3 potential values:

  • 100% windows
  • 1024px (for a better look)
  • content width

I was able to accomplish # 1 and # 2 using CSS property widths: 100% and min-width: 1024px. I can also accomplish # 2 and # 3 by setting display: inline-block and min-width: 1024px. However, I was unable to get all three: if I add width: 100% to the display and min-width properties, it overrides the effect of the size of the content of the inline-block's display child content and gives me just 100% width, even if that means the content overflows.

I know I can hide the overflow or provide scrolling for the div div, but I want the div to expand as needed or to the full width of the window, whichever is larger - but no more than 1024px.

Edit: Please note that the content loaded in the div can be less than 1024px. However, the div itself shouldn't be smaller than that as it won't blend well with the look of the rest of the page anymore.

+3


source to share


3 answers


This can be done by adding another div on top of the first one:

<div class="container2">
    <div class="container">
    </div>
</div>

      

CSS



.container2{min-width:100%;  display:inline-block;}
.container{min-width:1024px; width:100%;}

      

http://jsfiddle.net/om10t3gn/4/

+3


source


You can augment your second sentence with a virtual pseudo element to achieve the dimensions you require without using javascript

        .container {
            min-width: 1024px;
            display: inline-block;
        }

        .container::before {
            width: 100vw;
            display: block;
            content: ' ';
        }

      



Basically, it adds a zero-height element to the top of your container, which is the same width as your viewport, which is 100% of the width <body>

. So it adds # 1 to the existing solution, which already reaches # 2 and # 3.

And it doesn't use javascript and will stay correct with modifications.

+3


source


Use javascript to pick the largest value, use jQuery to assign that value to the width of the div container.

    var window_width = $(window).width();
    var container_width = $('.container').width();
    var default_width = 1024px;

    var max_width = Math.max(window_width, container_width, default_widht);

    $('.container').css('width', max_width);

      

+1


source







All Articles