CSS:多行浮点对齐未按预期工作

CSS: Multiline float alignment not working as desired

我的 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 来布置您的结构。那是一种不好的做法。

基本上,根据我的经验,float 会产生明显的副作用,直接影响您的网页。

更好,在这里解释:

为了简化您的回答,您必须将每一行包裹在 <div>...</div> 标签内。 但是随着 float 属性,parent 的高度变为零。

这里有一个简单的解决方案(display:inline-block),适合您:

<html>

<head>

 <style>
  label, input[type=text], button {
   display: inline-block;
  }
 
 </style>

</head>

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

</html>

很好,你对 lebel 使用 float,但请记住它使用的是行高,并且 lebel 和文本输入的行是不一样的。当您在代码中使用另一个 'br' 时,您就会明白。

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

  <br><br>

  <label for="anotherInput">LABEL 2</label>
</body>

您可以使用 'display:inline-block'

而不是使用浮点数
  label, input[type=text], button {
    display: inline-block;
  }

如果 float 只是您正在寻找的解决方案,那么您必须了解 clear 属性 或 CSS。 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>

<head>

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

</head>

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

</html>