html - CSS:多行 float 对齐不按预期工作

标签 html css alignment css-float

我的 html 文档中有多行,每一行都向左浮动。但是我的第二行没有正确地左对齐——很难解释,最好检查一下代码和 jsfiddle:

https://jsfiddle.net/0j8kd4c3/

<html>

<head>

    <style>

        label, input[type=text], button {
            float: left;
        }

    </style>

</head>

<body>

    <label for="input1">LABEL 1</label>
    <input id="input1" type="text" />
    <button type="button">BUTTON</button>

    <br />

    <label for="input2">LABEL 2</label>
    <input id="input2" type="text" />

    <br />

    <label for="input3">LABEL 3</label>
    <input id="input3" type="text" />

</body>

</html>

将第一行包裹在 div 容器中无济于事,那我该怎么办?

请注意,它再次适用于第 3 行,这让我感到困惑。

最佳答案

如果 float 只是您正在寻找的解决方案,那么您必须了解 CSS 的 clear 属性。 https://www.w3schools.com/cssref/pr_class_clear.asp

简单地说,在新行的 div 上应用 clear:both

这里是完整的解决方案:

<html>

<head>

	<style>
	
		label, input[type=text], button {
			float: left;
		}
        .next{
          clear: both;
        }
	
	</style>

</head>

<body>
	<label for="input">LABEL 1</label>
	<input id="input" type="text" />
	<button type="button">BUTTON</button>
  
	<div class="next"></div>
	<label for="anotherInput">LABEL 2</label>
</body>

</html>

关于html - CSS:多行 float 对齐不按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57741583/

相关文章:

javascript - 固定导航栏时隐藏绝对定位的 div

javascript - 2 带有动态内容滚动后固定右面板的面板布局

css - Gantry 5 网格系统与 Bootstrap 4 中的相同

css - 位置背景图像中心底部有一些偏移

html - 如何在链接下加点

html - 为什么我的表格在我的导航栏之后不在新行开始?

javascript - 如何使用 CSS 或 JavaScript 将带有图标和换行(!)文本的面板居中?

html - img 没有反应

html - 如何在html中删除悬停图像的轮廓

html - 宽屏幕上的 CSS float 对齐不均匀