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

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>


当前回答

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

其他回答

要居中一个位置:绝对属性,你需要设置left:50%和margin-left: -50%的div宽度。

<!-- for horizontal -->
<style>
div.center{
 width:200px;
 left:50%;
 margin-left:-100px;
 position:absolute;
}
</style>


<body>
 <div class='center'>
  should be centered horizontaly
 </div>
</body>

对于垂直中心绝对,你需要做同样的事情,而不是用左边,只是用顶部。 (注意:html和body必须有min-height 100%;)

<!-- for vertical -->
<style>
 body,html{
  min-height:100%;
 }
 div.center{
  height:200px;
  top:50%;
  margin-top:-100px;
  position:absolute;
 }
</style>

<body>
 <div class='center'>
  should be centered verticaly
 </div>
</body>

并且可以两者结合使用

   <!-- for both -->
 <style>
 body,html{
  min-height:100%;
 }
 div.center{
  width:200px;
  height:50px
  left:50%;
  top:50%;
  margin-left:-100px;
  margin-top:-25px;
  position:absolute;
 }
</style>


<body>
 <div class='center'>
  should be centered
 </div>
</body>
    <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;

#parent
{
    position : relative;
    height: 0;
    overflow: hidden;
    padding-bottom: 56.25% /* images with aspect ratio: 16:9  */
}

img 
{
    height: auto!important;
    width: auto!important;
    min-height: 100%;
    min-width: 100%;
    position: absolute;
    display: block;
    /*  */
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
    margin: auto;
}

我不记得我在哪里看到了上面列出的居中方法,使用负的上、右、下、左值。 对我来说,在大多数情况下,这个技巧是最好的。

当我使用上面的组合时,图像的行为就像一个背景图像,具有以下设置:

background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;

关于第一个例子的更多细节可以在这里找到: 使用CSS维护div的纵横比

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

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

绝对位置将其从流中取出,并将其放在父元素的0x0处(最后一个块元素具有绝对位置或相对位置)。

我不确定你到底想要完成什么,它可能是最好的设置li到一个位置:相对,这将居中他们。考虑到当前的CSS

请登录http://jsfiddle.net/rtgibbons/ejRTU/玩它