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

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>


当前回答

对于这种情况,我认为下面的代码就足够了:

    ul#slideshow li {
      position: absolute;
      left: 0;
      right: 0;
    }

其他回答

越简单越好:

img {
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto auto;
            position: absolute;
}

然后你需要将你的img标签插入到一个运动位置:相对属性的标签中,如下所示:

<div style="width:256px; height: 256px; position:relative;">
      <img src="photo.jpg"/>
</div>

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>

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

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

只需在父元素上使用display: flex和justify-content: center即可

body { text-align: center; } #slideshowWrapper { margin-top: 50px; text-align: center; } ul#slideshow { list-style: none; position: relative; margin: auto; display: flex; justify-content: center; } ul#slideshow li { position: absolute; } ul#slideshow li img { border: 1px solid #ccc; padding: 4px; height: 100px; } <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> <!-- Images from Unsplash-->

您可以在JSFIDDLE中找到这个解决方案

如果你不知道元素的宽度,你可以使用下面的代码:

<body>
<div style="position: absolute; left: 50%;">
    <div style="position: relative; left: -50%; border: dotted red 1px;">
        I am some centered shrink-to-fit content! <br />
        tum te tum
    </div>
</div>

演示在小提琴:http://jsfiddle.net/wrh7a21r/

来源:https://stackoverflow.com/a/1777282/1136132