How to center a “position: absolute” element

2018-12-31 05:40发布

I'm having a problem centering an element that has the attribute position set to absolute. Does anyone know why the images are not centered?

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="img/dummy1.JPG" alt="Dummy 1" /></li>
      <li><img src="img/piano_unlicened.JPG" alt="Dummy 2" /></li>
    </ul>
  </div>
</body>

24条回答
浪荡孟婆
2楼-- · 2018-12-31 06:41
    <div class="centered_content"> content </div>
    <style type="text/css">
    .centered_content {
       text-align: center;
       position: absolute;
       left: 0;
       right: 0;
    }
    </style>

see demo on: http://jsfiddle.net/MohammadDayeh/HrZLC/

text-align: center; works with a position: absolute element when adding left: 0; right: 0;

查看更多
像晚风撩人
3楼-- · 2018-12-31 06:42

The simpler, the best:

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

Then you need to insert your img tag into a tag that sports position:relative property, as follows:

<div style="width:256px; height: 256px; position:relative;">
      <img src="photo.jpg"/>
</div>
查看更多
梦寄多情
4楼-- · 2018-12-31 06:42

Using left: calc(50% - Wpx/2); where W is the width of the element works for me.

查看更多
有味是清欢
5楼-- · 2018-12-31 06:44

If you don't know the width of the element you can use this code:

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

Demo at fiddle: http://jsfiddle.net/wrh7a21r/

Source: https://stackoverflow.com/a/1777282/1136132

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 06:44

Use margin-left: x%; where x is the half of the width of the element.

查看更多
像晚风撩人
7楼-- · 2018-12-31 06:45

Div vertically and horizontally aligned center

top: 0;
bottom: 0;
margin: auto;
position: absolute;
left: 0;
right: 0;

Note : Elements should have width and height to be set

查看更多
登录 后发表回答