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

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>


当前回答

或者你现在可以使用flex box与位置绝对:

.parent {
    position: relative;
    display: flex;
    justify-content: center;
}

.child {
    position: absolute;
}

其他回答

你可以试试这种方法:

* { margin: 0px; padding: 0px; } #body { height: 100vh; width: 100vw; position: relative; text-align: center; background-image: url('https://s-media-cache-ak0.pinimg.com/originals/96/2d/ff/962dff2247ad680c542622e20f44a645.jpg'); background-size: cover; background-repeat: no-repeat; } .text { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height:100px; display: inline-block; margin: auto; z-index: 999999; } <html> <body> <div id="body" class="container-fluid"> <!--Background--> <!--Text--> <div class="text"> <p>Random</p> </div> </div> </body> </html>

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

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

使用 左:calc(50% - Wpx/2);其中W是元素的宽度。

或者你现在可以使用flex box与位置绝对:

.parent {
    position: relative;
    display: flex;
    justify-content: center;
}

.child {
    position: absolute;
}

正如许多人所说的⬇️

.element {
  position: absolute;
  left: 0;
  top: 0;
  transform: translate(-50%, -50%);
}

应该工作。但是请注意,.element必须位于具有position: relative;(以防你不想把它放在整个HTML页面的中心)

供你参考:我做了一个CSS居中的伪库。我需要它给我的后辈开发人员。所以,尽管去看看吧。http://dev.solcode.net/centercss/