我有一个问题,居中有一个元素的属性位置设置为绝对。 有人知道为什么这些图像没有居中吗?

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>


当前回答

在CSS中,居中一些绝对定位的东西是相当复杂的。

ul#slideshow li {
    position: absolute;
    left:50%;
    margin-left:-20px;

}

将左边距更改为要居中的元素宽度的一半(负)。

其他回答

可能是最短的

position:absolute;
left:0;right:0;top:0;bottom:0;
margin:0 auto;

相对对象中的绝对对象是相对于它的父对象的,这里的问题是你需要一个静态宽度容器#slideshowWrapper,其余的解决方案就像其他用户说的

body {
    text-align: center;
}

#slideshowWrapper {
    margin-top: 50px;
    text-align:center;
    width: 500px;
}

ul#slideshow {
    list-style: none;
    position: relative;
    margin: auto;
}

ul#slideshow li {
    position: relative;
    left: 50%;
}

ul#slideshow li img {
    border: 1px solid #ccc;
    padding: 4px;
    height: 450px;
}

http://jsfiddle.net/ejRTU/10/

我不确定你想要完成什么,但在这种情况下,只是增加宽度:100%;到你的ul#slideshow li将做的把戏。

解释

The img tags are inline-block elements. This means that they flow inline like text, but also have a width and height like block elements. In your css there are two text-align: center; rules applied to the <body> and to the #slideshowWrapper (which is redundant btw) this makes all inline and inline-block child elements to be centered in their closest block elements, in your code these are li tags. All block elements have width: 100% if they are the static flow (position: static;), which is default. The problem is that when you tell li tags to be position: absolute;, you take them out of normal static flow, and this causes them to shrink their size to just fit their inner content, in other words they kind of "lose" their width: 100% property.

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

如果你知道宽度,你也可以使用第三个选项,它将居中。

我最喜欢的绝对居中任何元素或元素组的方法是对它们的容器进行绝对定位,使其成为相对容器的高度和宽度,然后使用flex来对齐其中的元素。

在这种情况下:

body {
  position: relative; /* OPTIONAL */
}

#slideshowWrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row; /* OPTIONAL IF ONLY ONE ELEMENT */
  justify-content: center;
  align-items: center;
}

希望有帮助,干杯。