supersize
supersize

Reputation: 14783

center div with position absolute with just css without knowing the width

I would like to center different images which are shown and hidden, depending on how the user clicks. What I did to center an image was:

img { 
  margin-left: auto; 
  margin-right: auto; 
  display: block;
}

which worked fine. But it does not work for a position: absolute; Is there a css only way to center a position: absolute div horizontally in the middle of body or parent without knowing the width?

Upvotes: 0

Views: 282

Answers (4)

Nils Kaspersson
Nils Kaspersson

Reputation: 9464

Give the element position: absolute and position it 50% from the left edge of the screen, then use transform: translate to move it 50% of its width to the left.

Demo:

HTML:

<div class="center"></div>

CSS:

.center {
  position: absolute;
  top: 0;
  left: 50%;
  
  transform: translateX(-50%);
}

Here's a pen with this.

Here's the browser support for 2d transforms, and information about which vendor prefixes you need.

You can also use transform: translate3d to center elements vertically with the same logic. The CSS would then look like this:

.center {
  position: absolute;
  top: 50%;
  left: 50%;  
  transform: translate3d(-50%, -50%, 0);
}

Upvotes: 1

Andrei
Andrei

Reputation: 3106

The only way i know is using an additional div, like this:

http://jsfiddle.net/tTAG5/1/

HTML:

<div class="target">
<div class="wrapper"></div>
</div>

CSS:

.wrapper{
    width:100px;
    height:100px;
    background:blue;
    margin:0 auto;
    margin-left:-50%;
}
.target{
    position:absolute;
    left:50%;
}

What this does is:

  • set left:50% on your main div
  • add your divs contents in another wrapper div element like shown in demo above
  • set margin-left:-50% on the wrapper div

Upvotes: 0

King King
King King

Reputation: 63327

For absolutely positioned element, you can set the margin:auto in combination with left:0 and right:0 (for horizontally centered) or top:0 and bottom:0 (for vertically centered):

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

Demo.

Upvotes: 5

Bob Brinks
Bob Brinks

Reputation: 1392

You can use:

padding-left: 50%;
margin-left: -(half the width of your image)px

It's not the cleanest solution it's probably not the right scenario for absolute positioning.

Upvotes: -1

Related Questions