不能将两个div放在一行而不会弄乱容器的高度

时间:2013-02-17 17:22:13

标签: css html height

我试图将两个div放在一行但是当我设法做到这一点时 - 主容器的高度未正确调整:

<div class="container">
    <div class="info">Text</div>
    <div class="controls">
        <button value="Accept">Accept</button>
        <button value="Decline">Decline</button>
    </div>
</div>

CSS:

.container{
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
border:1px solid #800000;

margin: 8px;
height:auto;
}

.info{
display: inline-block;
vertical-align: middle;
text-align: center;
}

.controls{
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
width: 130px;
padding: 8px;
border-left: 1px solid #000;
background-color: #D4D0C8;
float: right;
}

button{
width:100%; // what ever you want it to be
}

jsfiddle

如何修复容器高度?

3 个答案:

答案 0 :(得分:1)

这是基于浮动的布局的常见问题:容器不会伸展以适应浮动子项的高度。这个问题有两个简单的解决方案:

  • 将div添加到clear:both(正如AliRiza在另一个答案中建议的那样)。
  • overflow:auto添加到容器中。

我主张使用后一种方法,因为它不涉及为了呈现而添加HTML元素。 See more info on this here

可以这样实现:

.container {
    overflow:auto;
}

JS Fiddle Example

答案 1 :(得分:0)

在容器div的末尾添加<div style="clear:both;"></div>

<div class="container">
    <div class="info">Text</div>
    <div class="controls">
        <button value="Accept">Accept</button>
        <button value="Decline">Decline</button>
    </div>
    <div style="clear:both;"></div>
</div>

已编辑DEMO

答案 2 :(得分:0)

CSS

<style>
div{
width:100px;
height:100px;
display:inline-block;
border:1px solid #ccc;
vertical-align:top;
}
</style>

HTML

<div>your div 1</div>
<div>Your div 2</div>

垂直对齐是为了保持在顶部,如果你添加不同数量的文字和图像,因为它下降大声笑