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

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>


当前回答

可能是最短的

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

其他回答

使用margin-left: x%;其中x是元素宽度的一半。

正如许多人所说的⬇️

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

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

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

我最喜欢的绝对居中任何元素或元素组的方法是对它们的容器进行绝对定位,使其成为相对容器的高度和宽度,然后使用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;
}

希望有帮助,干杯。

可能是最短的

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

html, body, ul, li, img { box-sizing: border-box; margin: 0px; padding: 0px; } #slideshowWrapper { width: 25rem; height: auto; position: relative; margin-top: 50px; border: 3px solid black; } ul { list-style: none; border: 3px solid blue; } li { /* center horizontal */ position: relative; left: 0; top: 50%; width: 100%; text-align: center; font-size: 18px; /* center horizontal */ border: 3px solid red; } img { border: 1px solid #ccc; padding: 4px; //width: 200px; height: 100px; } <body> <div id="slideshowWrapper"> <ul id="slideshow"> <li><img src="http://via.placeholder.com/350x150" alt="Dummy 1" /></li> <li><img src="http://via.placeholder.com/140x100" alt="Dummy 2" /></li> <li><img src="http://via.placeholder.com/200x100" alt="Dummy 3" /></li> </ul> </div> </body>