How to make a div align to the right side of the parent while maintaining its vertical position?

sbichenko picture sbichenko · Oct 4, 2012 · Viewed 85.8k times · Source

Please refer to this handy diagram I drew:

enter image description here

div1's height is unknown. div3's width is fluid; it should never overlap div2. Both div1 and div2 have the same width and are horizontally centered via margin: auto. How can I position div3 so that it aligns to the right side of body (no matter how wide body is) while sharing vertical position with div2? (Using CSS)

Answer

Gabriele Petrioli picture Gabriele Petrioli · Oct 4, 2012

.div1{
    margin:0 auto;
    width:100px;
    height:50px;
    border:5px solid #995555;
}
.div2{
    width:100px;
    margin:0 auto;
    border:5px solid #aaaa55;
    height:200px;
}
.div3{
    float:right;
    width:50px;
    height:100px;
    border:5px solid cyan;
}
<div class="div1">div1</div>
<div class="div3">div3</div>
<div class="div2">div2</div>

Demo also at http://jsfiddle.net/XjC9z/1/