Xen*_*ong 47 html css css-position css3
最近我遇到过这种用于将元素水平和垂直定位到中心的方法.但是,我无法弄清楚每个房产的作用.有人能够向我解释对设置的影响是什么top:0, bottom:0, left:0, right:0?
(如果您能够使用外行术语来解释它或提供说明性图像,那将会很棒.)
另外,将显示设置为表格的用途是什么?
.absolute-center {
position: absolute;
display: table;
height: auto;
width: 500px;
margin: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
border: solid 1px red;
}Run Code Online (Sandbox Code Playgroud)
<p class="absolute-center">What is this sorcery?</p>Run Code Online (Sandbox Code Playgroud)
Joe*_*ida 44
你可以将css减少到这个:
.absolute-center {
position:absolute;
width: 500px;
height: 100px;
margin: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
border: solid 1px red;
}Run Code Online (Sandbox Code Playgroud)
<p class="absolute-center">What is this sorcery?</p>Run Code Online (Sandbox Code Playgroud)
absolute具有类似属性的元素bottom: 0; top: 0; left: 0; right: 0;将填充所有空间.
那么,这里的秘密/巫术是什么?
您正在定义元素的宽度和高度.因此,即使他想要填满所有空间,他也会受到你的宽度和高度的限制.
秘诀是margin: auto,为什么?因为元素将填充剩余间距和边距.这样,因为您定义了宽度和高度,它将具有该大小,但边距将以工作方式填充容器/父级的其余部分,auto两侧大小相等.
因为margin:auto您需要定义宽度和高度.
Iva*_*ova 11
我们打破一下吧:
如果您有以下CSS(我将其应用于您当前的标记):
.absolute-center {
position:absolute;
height: auto;
margin: auto;
background: red;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
Run Code Online (Sandbox Code Playgroud)
你可以看到,div.absolute-center填满整个父元素(在这种情况下body),只需通过设置的所有属性top,bottom,right和left.
演示:http://jsfiddle.net/0osLv27k/
因此,当我们width(另外height)添加到前一个CSS时,该元素仅限于此大小.
演示:http: //jsfiddle.net/0osLv27k/1/
最后,神奇margin: auto的元素使元素居中.
演示:http://jsfiddle.net/0osLv27k/2/