如何使“位置:绝对"居中元素

2022-01-30 00:00:00 centering html css css-position

我在将属性 position 设置为 absolute 的元素居中时遇到问题.有谁知道为什么图片不居中?

I'm having a problem centering an element that has the attribute position set to absolute. Does anyone know why the images are not centered?

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>

推荐答案

如果你设置了宽度,你可以使用:

If you have set a width you may use:

position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
text-align: center;

相关文章