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

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”的中心元素的简单且最佳的解决方案

身体,html { 最小高度:100%; } div.center { 宽度:200 px; 左:50%; Margin-left:-100px;/*这是元素宽度的50% 位置:绝对的; 背景:# ddd; 边框:1px实体#999; 身高:100 px; text-align:中心 } <时尚> > < /风格 身体< > < div class = >“中心” 应该垂直居中 < / div > 身体< / >

其他回答

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

正如许多人所说的⬇️

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

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

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

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

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

下面是使用“position: absolute”的中心元素的简单且最佳的解决方案

身体,html { 最小高度:100%; } div.center { 宽度:200 px; 左:50%; Margin-left:-100px;/*这是元素宽度的50% 位置:绝对的; 背景:# ddd; 边框:1px实体#999; 身高:100 px; text-align:中心 } <时尚> > < /风格 身体< > < div class = >“中心” 应该垂直居中 < / div > 身体< / >

这招对我很管用:

position: absolute;
left: 50%;
transform: translateX(-50%);