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

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>


当前回答

你可以试试这种方法:

* { 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>

其他回答

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

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

这招对我很管用:

position: absolute;
left: 50%;
transform: translateX(-50%);
    <div class="centered_content"> content </div>
    <style type="text/css">
    .centered_content {
       text-align: center;
       position: absolute;
       left: 0;
       right: 0;
    }
    </style>

参见demo: http://jsfiddle.net/MohammadDayeh/HrZLC/

text-align:中心;工作与位置:绝对元素时添加左:0;右:0;

将“position: absolute”元素居中。

.your-element {
  position: absolute;
  left: 0;
  right: 0;
  text-align: center; // or this ->  margin: 0 auto;
}

目前似乎有两种解决方案;边距居中,位置居中。这两种工作都很好,但是如果您想要相对于这个居中元素的绝对位置,则需要使用绝对位置方法,因为第二个元素的绝对位置默认为所定位的第一个父元素。像这样:

<!-- CENTERED USING MARGIN -->
<div style="width:300px; height:100px; border: 1px solid #000; margin:20px auto; text- align:center;">
    <p style="line-height:4;">width: 300 px; margin: 0 auto</p>
    <div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:-20px; left:0px;">
        <p style="line-height:4;">Absolute</p>
    </div>
</div>

<!-- CENTERED USING POSITION -->
<div style="position:absolute; left:50%; width:300px; height:100px; border: 1px solid #000; margin:20px 0 20px -150px; text-align:center;">
    <p style="line-height:2;">width:300px; position: absolute; left: 50%; margin-left:-150px;</p>
    <div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:0px; left:-105px;">
        <p style="line-height:4;">Absolute</p>
    </div>
</div>

直到我读到这篇文章,使用边距:0自动技术,在我的内容的左边建立一个菜单,我必须在右边建立一个相同宽度的列来平衡它。不漂亮。谢谢!