为什么“什么”这个词向左浮动时会下降到下一行? “为什么”除了“为什么”这个词之外没有?它们都是段落。我是一个 html/css 菜鸟,还在学习中,谢谢
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<div class="container">
<h1>I love carrots</h1>
<p id="what">what</p>
<p id="why">why</p>
</div>
</body>
</html>
style1.css
.container{
border: solid;
overflow: hidden;
}
.container #what{
float: left;
}```
[enter image description here](https://i.stack.imgur.com/ZwHtz.png)
I was expecting to be beside the word why and not go next line
问题在于
<p>
标签的边距相互干扰。如果您检查开发工具中的元素,您会发现当 p#why
浮动时,p#what
仍然延伸到页面的左边缘,因此它们有点重叠。
你可以
p#why
,或者p#why
的下边距并删除 p#what
或者你当然可以选择像 Flexbox 这样的单独的布局方法,但这是使用浮动的方法。
.container {
border: solid;
overflow: hidden;
}
.container + .container {
margin-top: 20px;
}
/* original */
.container #what {
float: left;
}
/* option 1 */
.container #what2,
.container #why2 {
float: left;
}
/* option 2 */
.container #what3 {
float: left;
margin-top: 0;
}
.container #why3 {
margin-bottom: 0;
}
<figure>
<div class="container">
<h1>I love carrots</h1>
<p id="what">what</p>
<p id="why">why</p>
</div>
<figcaption>original</figcaption>
</figure>
<figure>
<div class="container">
<h1>I love carrots</h1>
<p id="what2">what</p>
<p id="why2">why</p>
</div>
<figcaption>option 1</figcaption>
</figure>
<figure>
<div class="container">
<h1>I love carrots</h1>
<p id="what3">what</p>
<p id="why3">why</p>
</div>
<figcaption>option 2</figcaption>
</figure>