3

I know this title is probably about the most common on SO, but I seem to have a very specific problem that I can't find documented.

I have a div that I want to be exactly square, so I followed the CSS advice in this answer. I also want a child div to fill this space, so I've followed all the standard guidelines of having a clear:both div in a wrapper, etc, but my child div is still not filling its parent. The problem is the height: 0 of the parent div - is there a solution to this but still maintaining the exact square (preferably pure CSS, I'm aware there are JS solutions). Example of this is at this fiddle.

Community
  • 1
  • 1
ChrisW
  • 4,970
  • 7
  • 55
  • 92

4 Answers4

8

You can give the inner box an absolute position and set it to conform to the edges of the containing box:

.box div {
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    border: 1px solid black;
    display: block;
    background-color: rgba(0,0,0,0.1);
}

jsfiddle

Not sure if it's any better to what you proposed, maybe if you wanted content in the box?

gaynorvader
  • 2,619
  • 3
  • 18
  • 32
  • Thanks! This seems like a pretty robust approach. I'll do some experimenting and see which result seems better :) – ChrisW Jun 24 '15 at 11:44
  • 1
    As you say, this does work better when I want more content. The simplistic way I came up with breaks when there's more content, because of the effect of padding on the content in the child div – ChrisW Jun 24 '15 at 12:08
2

If you're not too worried about support then using vh, vw, or vmin would be a good alternative. Since height would actually be set you could easily set the child element to fill the parent.

CSS:

.parent {
  width: 50vmin;
  height: 50vmin;
  background-color: blue;
  margin: 0 auto;
}

.child {
  width: 100%;
  height: 100%;
  background-color: red;
}

HTML:

<div class='parent'>
  <div class='child'></div>
</div>

Here's an example. I like vmax, but it's not as well supported as vmin, vh, and vw.

David Mann
  • 2,074
  • 1
  • 17
  • 17
1

This padding trick for responsive boxes work with absolute positioning.

css-padding-trick-responsive-intrinsic-ratios

So use absolute positioning for inner div.

.box {
 ...
  position: relative;
}

.box div {
  ...
   position: absolute;
   left: 0;
   top: 0;
}
Felix A J
  • 6,300
  • 2
  • 27
  • 46
  • Is this different to the [very good answer](http://stackoverflow.com/a/31025326/889604) posted below? – ChrisW Jun 24 '15 at 11:42
  • didnt noticed. anyway `right: 0; bottom: 0;` is not required as mentioned. height:100% will work – Felix A J Jun 24 '15 at 11:55
0

Adding padding-bottom: 100% to the child div does fill the space and seems to be a fix; the updated jsfiddle reflects this

ChrisW
  • 4,970
  • 7
  • 55
  • 92