984 Stimmen

Wie zentriert man ein "Position: absolut"-Element?

Ich habe ein Problem beim Zentrieren eines Elements, das das Attribut position eingestellt auf absolute . Weiß jemand, warum die Bilder nicht zentriert sind?

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>

67voto

cutez7boyz Punkte 781

Ein einfacher CSS-Trick, einfach hinzufügen:

width: 100%;
text-align: center;

Dies gilt sowohl für Bilder als auch für Text.

46voto

Deplake Punkte 825

Das hat bei mir funktioniert:

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

43voto

flyingpluto7 Punkte 974

So zentrieren Sie ein "Position: absolut"-Element.

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

30voto

Rednas Punkte 609

Um ein position:absolute-Attribut zu zentrieren, müssen Sie left:50% und margin-left: -50% der Breite des div einstellen.

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

für die vertikale Mitte absolut müssen Sie die gleiche Sache Knospe nicht mit links nur mit oben zu tun. ( HINWEIS: html und body müssen min-height 100% haben; )

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

und können für beide kombiniert werden

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

28voto

Sie können das Attribut "transform" verwenden:

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

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X