Skip to content

Instantly share code, notes, and snippets.

@williamdodson
Created August 22, 2012 18:44
Show Gist options
  • Save williamdodson/3428263 to your computer and use it in GitHub Desktop.
Save williamdodson/3428263 to your computer and use it in GitHub Desktop.
A pretty cool technique which allows to position elements side by side. Kind of absolute positioning but with rows which are aware of each other.
<h1>Container-relative floats</h1>
<p><small>Forked from <a href="http://codepen.io/edge0703/pen/KkIcg">this pen</a></small></p>
<p>The value of <code>margin-right: -100%</code> makes sure that every subsequent element starts right at the left edge of the container and isn't aware of its preceding sibling. This way the order of the elements within each row in the HTML code doesn't matter (try to move .item2 to the top or delete it). Furthermore you just need to assign <code>clear: left</code> to start a new row. Kind of absolute positioning but with rows which are aware of each other.</p>
<div class="wrapper">
<!-- first row -->
<div class="item item1">Element<br><br><br></div>
<div class="item item2">Element<br><br></div>
<div class="item item3">Element<br><br><br><br></div>
<!-- second row -->
<div class="row item item4">Element<br><br><br><br></div>
<div class="item item5">Element<br><br></div>
<div class="item item6">Element<br><br><br></div>
</div>
<p class="src">Inspiration: <a href="http://www.palantir.net/blog/responsive-design-s-dirty-little-secret">http://www.palantir.net/blog/responsive-design-s-dirty-little-secret</p>
.row {
clear: left; /* Starts a new line */
}
.item {
float: left;
margin-right: -100%;/* Every element needs that */
}
.item1 {
width: 20%;
background: red;
}
.item2 {
width: 30%;
margin-left: 20%; /* The sum of the widths of the preceding elements */
background: blue;
}
.item3 {
width: 50%;
margin-left: 50%; /* The sum of the widths of the preceding elements: 20% + 30% */
background: green;
}
.item4 {
width: 10%;
margin-left: 0;
background: yellow;
}
.item5 {
width: 80%;
margin-left: 10%; /* The sum of the widths of the preceding elements */
background: magenta;
}
.item6 {
width: 10%;
margin-left: 90%; /* The sum of the widths of the preceding elements: 10% + 80% */
background: orange;
}
/* Just for styling purposes */
.src {clear: left; padding-top: 1em}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment