为什么使用浮动时文本不是垂直对齐的?

Why isn't the text vertically in line when using a float?

请看下面的HTML:

#container
{
  height: 60%;
  width: 100%;
  background-color:green;
}

#floatElement
{
  top:0px;
  height: 60%;
  width: 50%;
  background-color:red;
  float:right;
}
<html>
<head>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="floatElement">
<h1 >this is a test inside the float element</h1>
</div>
<div id="container">
<h1>test</h1>
</div>
</body>

</html>

这是结果。

为什么 float 中第一行文本上方有额外的 space,即为什么单词“text”和“this is a test inside a float element”不在一行?

我看过这里:https://developer.mozilla.org/en-US/docs/Web/CSS/float. The first image indicates that they should be in line. I have also Googled it and this is the closest I got: How to remove space at top of page when using float?。但是,它没有回答我的问题。

这是因为浏览器默认user agent stylesheet adds style for some elements, in that case I'd recommend using a reset css

现在回到问题,出现 space 是因为您使用的是浮点数,因此它将包含 h1 的默认边距。根据https://developer.mozilla.org/

The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow.

参考:https://developer.mozilla.org/en-US/docs/Web/CSS/float

虽然 div 元素的背景颜色不考虑其子元素的边距,但您必须为此使用填充。因为边距适用于元素边界之外,填充发生在边界之内。

这是一个例子:

#container { height: 60%; width: 100%; background-color:green; }

#container h1 {margin: 100px 0;}
<html>
<head>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="container">
<h1>test</h1>
</div>
</body>

</html>

如您所见,边距被父级的背景色省略,但仍然存在。

这是另一种情况。

#container { height: 60%; width: 100%; background-color:green; }

#container h1 {margin: 0; padding: 100px 0;}
<html>
<head>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="container">
<h1>test</h1>
</div>
</body>

</html>

您可以看到将填充添加到 h1

时会发生什么

这是您问题的答案,要使它们都在同一条线上飞行,请删除 h1

的边距

#container
{
  height: 60%;
  width: 100%;
  background-color:green;
}

#floatElement
{
  top:0px;
  height: 60%;
  width: 50%;
  background-color:red;
  float:right;
}

#floatElement h1, #container h1{
  margin-block-start: 0;
  /*you can also use margin: 0 in short */
}
<html>
<head>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="floatElement">
<h1 >this is a test inside the float element</h1>
</div>
<div id="container">
<h1>test</h1>
</div>
</body>

</html>