gpt4 book ai didi

javascript - 宽度为 100% 的相对定位不会使内容边到边

转载 作者:技术小花猫 更新时间:2023-10-29 11:54:16 26 4
gpt4 key购买 nike

这个问题我已经遇到很多次了,我决定问问。当我使用 width:100% 的相对定位时,内容不会在屏幕的边缘到边缘。另一方面,当我使用绝对定位或固定定位时,内容确实会边到边。为什么是这样?这是显示我的问题的示例代码:

#container {
display: block;
width: 100%;
position: relative;
height: 150px;
border: 1px solid;
text-align: center;
}
<div id='container'>
<br />
<br />^
<br />
<- Why do I have these spaces? ->
<br />\/
</div>

结果: enter image description here

我想要的: enter image description here

在谷歌搜索时,我确实遇到了 this page , 但看起来这个问题是由于未应用 text-align: center 引起的。

最佳答案

您必须重置默认的 body 边距/填充。

box-sizing: border-box; 也有助于在宽度计算中包含边框大小。

body {
margin: 0;
padding: 0;
}
#container {
display: block;
width: 100%;
position: relative;
height: 150px;
border: 1px solid;
text-align: center;
box-sizing: border-box;
}
<div id='container'>
<br />
<br />^
<br />
<- Why do I have these spaces? ->
<br />\/
</div>

引用:body Typical default display properties - box-sizing

关于javascript - 宽度为 100% 的相对定位不会使内容边到边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26980308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com