36

My goal is to display two <div>s side-by-side with the content from both <div>s aligned at the top. I do not want long text in the second <div> to wrap underneath the first one.

Finally, I do not want to set the width of the second <div> because I need the markup to work in different widths.

Sample markup is below and at http://jsfiddle.net/rhEyM/.

CSS

.left-div {
    float: left;
    width: 100px;
    height: 20px;
    margin-right: 8px;
    background-color: linen;
}
.right-div {
    float: left;
    margin-left: 108px;
    background-color: skyblue;
}​

HTML

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line
    up at the top, <b>[B]</b> Long text in right-div should not wrap
    underneath left-div, and <b>[C]</b> I do not want to specify a
    width of right-div. I don't want to set the width of right-div
    because this markup needs to work within different widths.
</div>

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466

3 Answers3

45

Try to Use Flex as that is the new standard of html5.

http://jsfiddle.net/maxspan/1b431hxm/

<div id="row1">
    <div id="column1">I am column one</div>
    <div id="column2">I am column two</div>
</div>

#row1{
    display:flex;
    flex-direction:row;
justify-content: space-around;
}

#column1{
    display:flex;
    flex-direction:column;

}


#column2{
    display:flex;
    flex-direction:column;
}
maxspan
  • 13,326
  • 15
  • 75
  • 104
  • I think this is the better solution, even if I know it does not work everytime (older Browsers and CSS3). But it gives you more flexibility concerning the height of the divs. – r00tandy Mar 25 '15 at 22:12
23

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • D'oh! You're exactly right. In my actual project, I wasn't setting the margin-left of the right div. That's all that's needed. Thanks. – Jonathan Wood Apr 04 '12 at 07:02
9

Try this : (http://jsfiddle.net/TpqVx/)

.left-div {
    float: left;
    width: 100px;
    /*height: 20px;*/
    margin-right: 8px;
    background-color: linen;
}
.right-div {

    margin-left: 108px;
    background-color: lime;
}​​

<div class="left-div">
    &nbsp;
</div>
<div class="right-div">
    My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'>&nbsp;</div>

Hints :

  • Just use float:left in your left-most div only.
  • No real reason to use height, but anyway...
  • Good practice to use <div 'clear:both'>&nbsp;</div> after your last div.
Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223