1

How do I horizontally center an element of variable width that needs to be on top of the other elements?

The accepted answer here Easy way to center variable width divs in CSS is good for centering variable width, but it pushes everything else down:

Normally I do:

position:absolute;
width:200px;
left:50%;
margin-left:-100px;

But this requires a set width.

(It's for a message box that pops up and needs to be centered on top of the other text.)

Community
  • 1
  • 1
user984003
  • 28,050
  • 64
  • 189
  • 285

6 Answers6

0

If you do not know the width of the block

  body /*or parent div selector*/{text-align:center};
    div{display:inline-block};

Else

div{margin:0 auto;display:block;}
zloctb
  • 10,592
  • 8
  • 70
  • 89
0

Use:

div {
    position:absolute;
    width: auto;
    left:50%;
}

http://jsfiddle.net/Hive7/93mAj/2

  • 1
    this will center the left border of the div, and not the middle of the div. so the div won't be centered, but slightly on the right (see your [updated fiddle](http://jsfiddle.net/93mAj/1/)) – Lorenzo Marcon Jul 16 '13 at 07:46
0
display: block;
margin: 0 auto;

= the top and bottom margin 0, and the left and right margin auto

Working Fiddle

Praveen
  • 55,303
  • 33
  • 133
  • 164
  • he doesn't want the div to push the other elements down.. he needs an absolute positioning, or at least a solution that takes the element out of the flow – Lorenzo Marcon Jul 16 '13 at 07:36
0

try this

    .div1{
    position:absolute;
    width:200px;
    left:50%;
    margin-left:-100px;
        background-color:red;
      text-align:Center;

    }
Falguni Panchal
  • 8,873
  • 3
  • 27
  • 33
0

You could create a wrapper:

#mydiv-wrapper {
    width: 75%;
    position: fixed;
    left: 50%;
    top: 50px;
    margin: 0 0 0 -37.5%;
    z-index: 10000;
    text-align: center;
}

this way you can insert inside it another div, without setting its width. The width will be automatically calculated.

#mydiv {
    display: table;
    margin: auto;
}

This won't push other elements down (thanks to position: absolute), and will appear on top of the other element (like an alert, just to be clear). Just change the top attribute to set the desired vertical position.

Test JSFiddle

Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63
0

I find this solution to be best if you don't want wrapper divs. This positions the left edge of the element to the middle of the parent and then shifts it back by half the width of the element.

div {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
Christian Hain
  • 619
  • 4
  • 11