part of my css layout sets div heights relative to widths so that the aspect ratio is the same for all screen sizes. this way i never specifically set the height of a div to a px value – the height is simply an aspect ratio of the width. if you have not come across this technique before, here is a good explanation.
onto my specific problem…
with this in mind i have created the following simple div which is twice as wide as it is high: (to see it in action please see this fiddle)
<html>
<head>
<style type="text/css">
.container
{
position:relative;
width:50%;/*half the width of the whole page*/
margin:auto;/*center the whole thing*/
}
.relative_container
{
background-color:blue;
position:absolute;
width:100%;
top:0;
left:0;
}
.set_height
{
width:100%;
height:100%;
margin-top:50%;/*aspect ratio 2:1*/
}
</style>
</head>
<body>
<div class='container'>
<div class='relative_container'>
<div class='set_height'></div>
</div>
</div>
</body>
</html>
all good so far. however i then want to add another identical div under the first. as you can see in this fiddle, i cannot get them to display any way other than on top of each other. no doubt the answer lies with clearing the divs as demonstrated here but i can’t figure it out.
Your
relative_containerclass is absolutely positioned, so it’s placing both of the divs at top:0, left:0 with the same width and height (so they’re on top of each other). This doesn’t make sense for what you’re doing.If you change the positioning to relative, and add
float: leftto your strangely namedrelative_container, you will get your desired behavior, as they will “float” to the leftmost possible place in their parent div.Also, your “clear” divs aren’t doing anything. The clear property tells other divs not to float to the right/left of the given div. If the width of your div is 100% (ie. it fills up the parent), then nothing can float next to it anyway.
Example 1: http://jsfiddle.net/NKRPe/13/
EDIT: This second example accomplishes the same task without using the dummy div. Note that either
padding-toporpadding-bottomcan be used.