首页 > 解决方案 > CSS:多行浮动对齐无法按预期工作

问题描述

我的 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 行,这让我感到困惑。

标签: htmlcssalignmentcss-float

解决方案


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

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

这是完整的解决方案:

<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>


推荐阅读