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

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>


当前回答

    <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;

其他回答

使用margin-left: x%;其中x是元素宽度的一半。

相对对象中的绝对对象是相对于它的父对象的,这里的问题是你需要一个静态宽度容器#slideshowWrapper,其余的解决方案就像其他用户说的

body {
    text-align: center;
}

#slideshowWrapper {
    margin-top: 50px;
    text-align:center;
    width: 500px;
}

ul#slideshow {
    list-style: none;
    position: relative;
    margin: auto;
}

ul#slideshow li {
    position: relative;
    left: 50%;
}

ul#slideshow li img {
    border: 1px solid #ccc;
    padding: 4px;
    height: 450px;
}

http://jsfiddle.net/ejRTU/10/

你可以使用"transform"属性:

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

越简单越好:

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>

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

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