Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: How does Width work as a percentage?

Tags:

css

width

parent

I'm having what I think is a weird problem. I have one div, inside a parent div, and I'm giving the child div a width of 100%, but it's not growing to the size of the parent div.

The parent div does not have a set width of any kind. So my question: does width in percentage only work when a parent element has a set width, or should it grow anyway?

CLARIFICATION:

Some may be wondering how the parent div has a width to grow to at all, if it itself does not have a set width. The reason is I have other siblings of the child element inside the parent div, with a set width to them, so the parent div has grown to meet those sibling widths.

CODE SAMPLE:

<div id="parent-div">
    <div id="child-element" style="width: 100%">Content</div>
    <div id="sibling" style="width: 250px"></div>
</div>

Child element is not growing to meet the parent div. The width of 100% is essentially not doing anything at all that I can tell. This is in IE7.

Thanks.

FOLLOW-UP: Thanks everyone for the answers. I'm busy testing on my end. I originally thought that parent div's only grow as wide as their children, but it turns out I was wrong given my example above, which I coded only to demonstrate my issue I'm having. In my case, my parent div has a position: fixed and bottom: 1px and right: 1px applied to it. From my tests, this appears to change the behavior of the parent div. No longer does it automatically stretch to the entire width of the page, but assumes the behavior I thought was the case anyway, which is the parent div expands only enough to accommodate its widest child. So that's the behavior I'm seeing now, but only because my parent div has a fixed position.

like image 471
MegaMatt Avatar asked Feb 04 '10 22:02

MegaMatt


1 Answers

Without having seen the rest of your CSS and HTML, I'm going to assume that what you've posted is all there is in your HTML and CSS.

In that case:

  • parent-div will definitely be as wide as the page, i.e. 100%.
  • child-element will also be as wide as the page, i.e. 100%, and be inside parent-div
  • sibling will have a width of 250px and be underneath child-element

If this is not the case, you've got other HTML or CSS interfering.

like image 180
Sarhanis Avatar answered Oct 01 '22 19:10

Sarhanis