Reputation: 5048
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.
Upvotes: 3
Views: 28268
Reputation: 2270
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.
Upvotes: 2
Reputation: 6490
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;
}
Upvotes: 1
Reputation: 5048
Adding padding-bottom: 100%
to the child div
does fill the space and seems to be a fix; the updated jsfiddle reflects this
Upvotes: 0
Reputation: 2657
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);
}
Not sure if it's any better to what you proposed, maybe if you wanted content in the box?
Upvotes: 8