gpt4 book ai didi

html - CSS 绝对居中

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

最近我遇到了这种方法,它用于将元素水平和垂直定位到中心。但是,我无法弄清楚每个属性在做什么。有人可以向我解释设置 top:0, bottom:0, left:0, right:0 有什么影响吗?

(如果您能够用通俗易懂的术语解释它或提供说明性图像,那就太好了。)

还有,设置display为table有什么用?

.absolute-center {
position: absolute;
display: table;
height: auto;
width: 500px;
margin: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
border: solid 1px red;
}
<p class="absolute-center">What is this sorcery?</p>

最佳答案

您可以将 css 缩减为:

.absolute-center {
position:absolute;
width: 500px;
height: 100px;
margin: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
border: solid 1px red;
}
<p class="absolute-center">What is this sorcery?</p>

absolute 元素的属性如 bottom: 0;顶部:0;左:0; right: 0; 将填充所有空间。

那么,这里的 secret /魔法是什么?

您正在定义元素的宽度和高度。所以,即使他想填满所有空间,他也会受到你的宽度和高度的限制。

secret 是 margin: auto,为什么?因为该元素将用边距填充剩余间距。这样,因为您定义了宽度和高度,所以它将具有该大小,但边距将以 auto 的工作方式填充容器/父级的其余部分,两侧大小相等。

因为 margin:auto 你需要定义宽度和高度。

关于html - CSS 绝对居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31311671/

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