显示两个<div>的并排</div>

时间:2012-04-04 06:47:26

标签: html css css-float

我的目标是并排显示两个<div>,其中<div>的内容在顶部对齐。我不希望第二个<div>中的长文本包含在第一个文本下面。

最后,我不想设置第二个<div>的宽度,因为我需要标记以不同的宽度工作。

示例标记位于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>

3 个答案:

答案 0 :(得分:30)

尝试使用Flex,因为这是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;
}

答案 1 :(得分:20)

我从第二个div中移除了浮动以使其工作。

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

答案 2 :(得分:9)

试试这个: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>

提示:

  • 只需在最左边的div 中使用float:left
  • 没有真正的理由使用height,但无论如何......
  • 在最后一个div之后使用<div 'clear:both'>&nbsp;</div>的好习惯。