css - 如何将div定位在另一个div之下

标签 css

我有两个 div:

<div><label for="1">Some really loooong text... Which breaks the second div. Which then appears shifted to the right.</label><input type="text" id="1" name"1"></div>
<div><label for="2">Shifted.</label><input type="text" id="2" name"2">

我使用以下 css 将标签 float 到输入文本字段的左侧:

label{
    width:200px;
    float:left;
}​

第二个 div 向左移动,而不是出现在第一个 div 的下方。它应该像第一个一样向左对齐。

示例如下:http://jsfiddle.net/qh37Y/

现在,如果我插入一个 clear:both; div,它就可以工作,但这是最佳实践吗?

.clearer {
    clear:both;
}
<div class="clearer"><label for="2">Shifted.</label><input type="text" id="2" name"2">​

参见此处:http://jsfiddle.net/ywUx6/

最佳答案

看起来这实际上是 div 高度的问题。

由于内容是 float 的,所以不会影响 div 的高度。因此,第二个 div 中的内容(不是 div 本身)环绕着第一个 div 的 float 标签。

clear: both 是可以接受的,但如果(例如)您想要将这些 div 用作双列布局中的一列,则会破坏布局。

我会建议 div { overflow: hidden; } 代替。这为 div 提供了一个新的框上下文,它不允许重叠边框,从而使 float 内容的高度影响到 div 的高度。

编辑:Fixed fiddle

关于css - 如何将div定位在另一个div之下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11003641/

相关文章:

html - 将图像放在 Navbar Bootstrap 旁边

javascript - 如何使用 JS 获取 "active page"状态类

javascript - 检查 CSS 类是否具有特定属性

html - html.textboxfor 中的图像

html - 我怎样才能使背景为动态的图像中显示的 0 左右的边框,我需要气泡的切割部分是透明的

javascript - Bootstrap 3.0 : Trigger when content moved under a with fix nav bar

html - 在 tbody 上应用 CSS hover(没有 th)

css - 如何设置显示 :inline 的 div 的固定宽度

asp.net - 将文本放在一个小按钮中

html - 在 mozilla 中显示嵌入式推文的突发问题