Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the CSS min-width attribute not force a div to have the specified minimum width?

Tags:

html

css

<html>
    <head>
        <style type="text/css">
            div {
                border:1px solid #000;
                min-width: 50%;
            }
        </style>
    </head>
    <body>
        <div>This is some text. </div>
    </body>
</html>

I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger. However, the border around the div stretches across the entire page width. This occurs in both IE and Firefox.

Suggestions?

like image 726
Thomas Owens Avatar asked Oct 13 '08 16:10

Thomas Owens


5 Answers

I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger.

min-width does not set a minimum starting width from which your block will grow; rather it limits how far the block can shrink.

In min-width: 50%;, the 50% is in reference to the containing block. I've never used percentages with min-width, but I find it can be useful with other units. For example if I have a block (like a column of text) that I want to be full width, but I don't ever want it to go below a minimum width, I could use something like {width: 100%; min-width: 250px;}.

Note the caveats on IE support mentioned by others.

like image 160
David Kolar Avatar answered Oct 23 '22 12:10

David Kolar


If you provide absolute positioning to the element, it will be 50% in Firefox. However, IE doesn't like the min-width or min-height attributes, so you will have to define width as 50% also for it to work in IE.

like image 41
Chris Serra Avatar answered Oct 23 '22 12:10

Chris Serra


Without min-width, your div will take whole page width, that is how display:block elements behave. Adding min-width cannot make it smaller.

Changing display property to absolute or float property to left will make the element to shrink to fit contents. Then, min-width start to make sense.

like image 32
buti-oxa Avatar answered Oct 23 '22 12:10

buti-oxa


To add to what Chris Serra said, in IE < 7 (and in 7? I can't keep track these days, but definitely < 8), width behaves exactly like min-width is supposed to behave.

like image 27
eyelidlessness Avatar answered Oct 23 '22 11:10

eyelidlessness


You are telling it that the minimum width is 50%. Since there is nothing else taking up the space, it will take all of it (except for margins).

If you give it a max-width of say 75%, firefox should constrain it to that. IE6 will still ignore it.

As David Kolar already said, many of us typically do not use percentages for min-width.

like image 22
18 revs, 10 users 77% Avatar answered Oct 23 '22 10:10

18 revs, 10 users 77%