我创建了一个快速简单的 html 文档来练习 float 思维,并提供了一个简单的示例,可以立即使用。但是奇怪的事情发生了。
我只想让 2 个 div 彼此相邻 float ,宽度和大小都相等。我使用了完全相同的标签和文字,以便完全轻松地了解它是如何工作的。然而,不知何故#content 在标题上方有填充,而#content1 没有,这使得“框”不同步。但是,当我向 #content1 添加仅 0.1px 的填充时,它们都排在一起并且具有完全相同的填充量?我似乎连最基本的概念都没有掌握......这是我使用的代码 -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Float</title>
<style>
p {
padding: 0;
margin: 0;
}
#content {
float: left;
width: 50%;
background-color: grey;
}
#content1 {
padding-top: 0.1px;
margin-left: 50%;
width: 50%;
background-color: grey;
}
</style>
</head>
<body>
<div id="content">
<h1>Ra ra banjo banjo</h1>
<p>Welcome to the Ra ra banjo banjo page. Ra ra banjo banjo. Ra ra banjo banjo. Ra ra banjo banjo.</p>
<p>(Ra ra banjo banjo)</p>
</div>
<div id="content1">
<h1>Ra ra banjo banjo</h1>
<p>Welcome to the Ra ra banjo banjo page. Ra ra banjo banjo. Ra ra banjo banjo. Ra ra banjo banjo.</p>
<p>(Ra ra banjo banjo)</p>
</div>
</body>
</html>
最佳答案
请记住,HTML 元素有一些默认样式,例如填充或边距,它们会影响元素的总宽度。您可以使用 *
使用 css 轻松更改这些内容,这将影响文档中的所有元素。
* {
padding: 0;
margin: 0;
border: none;
/*
etc., you can add here whatever you need to be a global style
and rewrite some things afterwards in the specific classes, ids, ...
*/
}
如果你在 float block ,你需要考虑元素的总数,所以不仅要考虑 width
属性,还要考虑它们的 padding
, margin
和 border
。如果您 float 的元素的汇总(总)宽度大于其父元素的宽度,则它们将不会 float 。
所以,在你的练习中它看起来像这样:
*, p {
padding: 0;
margin: 0;
}
#content {
float: left;
width: 50%;
background-color: grey;
}
#content1 {
/*
padding-top: 0.1px; - this is unnecessary
margin-left: 50%;
this margin makes the element 100% wide
(50% width + 50% margin-left), so it will not be floated to the
#content in your code as they would have the 150% of total width
and it's 50% more than the parent's width
(of course, parent's width is always 100%)
*/
width: 50%;
background-color: grey;
float: left;
}
关于html - 学习显示、位置和 float 。尝试了一种简单的花车练习,但没有成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41921303/