我有一个问题,居中有一个元素的属性位置设置为绝对。
有人知道为什么这些图像没有居中吗?
body {
text-align: center;
}
#slideshowWrapper {
margin-top: 50px;
text-align: center;
}
ul#slideshow {
list-style: none;
position: relative;
margin: auto;
}
ul#slideshow li {
position: absolute;
}
ul#slideshow li img {
border: 1px solid #ccc;
padding: 4px;
height: 450px;
}
<body>
<div id="slideshowWrapper">
<ul id="slideshow">
<li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
<li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
</ul>
</div>
</body>
如果你想让一个绝对元素居中
#div {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
width:300px; /* Assign a value */
height:500px; /* Assign a value */
margin:auto;
}
如果你想让一个容器从左到右居中,而不是从上到下
#div {
position:absolute;
left:0;
right:0;
width:300px; /* Assign a value */
height:500px; /* Assign a value */
margin:auto;
}
如果你想让一个容器从上到下居中,不管从左到右
#div {
position:absolute;
top:0;
bottom:0;
width:300px; /* Assign a value */
height:500px; /* Assign a value */
margin:auto;
}
更新截止2015年12月15日
好吧,几个月前我又学了一个新把戏。假设您有一个相对的父元素。
这就是你的绝对元素。
.absolute-element {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
width:50%; /* You can specify ANY width values here */
}
有了这个,我认为这是一个比我以前的解决方案更好的答案。因为你不需要指定宽度和高度。这个调整了元素本身的内容。
更新截止2021年4月23日
它不能回答OP关于绝对位置的问题,但如果你想要替代解决方案,有一个叫做flexbox的方法。举个例子。
#parent {
display:flex;
align-items:center;
justify-content:center;
}
它所做的是将容器转换为flex并将子项对齐到水平的居中通过使用justify-content:center而垂直的则使用align-items:center。它也支持现代浏览器,所以使用起来很安全。
不过,一定要先阅读flexbox的工作原理。
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox
支持Flexbox的浏览器
https://caniuse.com/flexbox
1-当你知道绝对定位元素的宽度。
width: 200px;
position: absolute;
left: 50%;
margin-left: -100px
2-当你不知道绝对定位元素的宽度时。响应性很好,但CSS3旧浏览器可能有问题。
position: absolute;
left: 50%;
-webkit-transform: translateX(-50%);
transform: translateX(-50%)
3-当你不知道绝对定位元素的宽度,但使它的父元素100%宽,这可能不符合设计。
position: absolute;
left: 0;
right: 0;
margin: auto
如果你知道宽度,你也可以使用第三个选项,它将居中。
在不知道positioned1元素的宽/高的情况下,仍然可以按如下方式对齐它:
例子
.child {
position: absolute;
top: 50%; /* position the top edge of the element at the middle of the parent */
left: 50%; /* position the left edge of the element at the middle of the parent */
transform: translate(-50%, -50%); /* This is a shorthand of
translateX(-50%) and translateY(-50%) */
}
值得注意的是,CSS Transform在IE9及以上版本中是受支持的。(为简洁起见,省略了供应商前缀)
解释
添加top/left为50%将元素的上/左边距移动到父元素的中间,(负)值为-50%的translate()函数将元素移动其大小的一半。因此,元素将被定位在中间。
这是因为顶部/左侧属性上的百分比值是相对于父元素的高度/宽度的(它正在创建一个包含块)。
而translate()转换函数上的百分比值是相对于元素本身的宽度/高度(实际上它指的是包围框的大小)。
对于单向对齐,使用translateX(-50%)或translateX(-50%)。
1. 具有非静态位置的元素。即相对的,绝对的,固定的值。