How to center a "position: absolute" element

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>

position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;

Without knowing the width / height of the positioned1 element, it is still possible to align it as follows:

EXAMPLE HERE

.child {
    position: absolute;
    top: 50%;  /* position the top  edge of the element at the middle of the parent */
    left: 50%; /* position the left edge of the element at the middle of the parent */

    transform: translate(-50%, -50%); /* This is a shorthand of
                                         translateX(-50%) and translateY(-50%) */
}

It's worth noting that CSS Transform is supported in IE9 and above. (Vendor prefixes omitted for brevity)


Explanation

Adding top / left of 50% moves the top/left margin edge of the element to the middle of the parent, and translate() function with the (negative) value of -50% moves the element by the half of its size. Hence the element will be positioned at the middle.

This is because a percentage value on top / left properties is relative to the height/width of the parent element (which is creating a containing block).

While a percentage value on translate() transform function is relative to width/height of the element itself (Actually it refers to the size of bounding box).

For unidirectional alignment, go with translateX(-50%) or translateY(-50%) instead.


1. An element with a position other than static . Ie relative , absolute , fixed values.


Centering something absolute ly positioned is rather convoluted in CSS.

ul#slideshow li {
    position: absolute;
    left:50%;
    margin-left:-20px;

}

Change margin-left to (negative) half the width of the element you are trying to center.

链接地址: http://www.djcxy.com/p/13232.html

上一篇: 我该如何做才能:固定好工作

下一篇: 如何以“位置:绝对”元素为中心