1

I'd like to know how I can center an element to the middle of the page horizontally.

Here is my code:

#item {
    height:400px;
    width:700px;
    background-color:white;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}

I'd like to center this so it looks like that:

example

(Centered horizontally and a few pixels below the header)

Thanks, M4DNE55

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
M4DNE55
  • 49
  • 1
  • 1
  • 5
  • 3
    `text-align: center; margin: 0 auto`? – Marc B Dec 15 '14 at 15:38
  • (a) is there anything else in that header?, (b) is the header fixed height, or dynamic?, (c) do u support IE8 and below? as others have said, horizontal is easy, but vertical is not ... doable, depending on those questions – PlantTheIdea Dec 15 '14 at 15:40

7 Answers7

1

Just add these

text-align:center; vertical-align:middle; display:table-cell;

0

Horizontal is easy, it's vertical that's a bother. To centre in-line elements such as text and images, use text-align:center;.

To centre divs you can use margin: 0 auto;

Andrei Nemes
  • 3,062
  • 1
  • 16
  • 22
0

To center something in general, use

margin:0px auto;

this is equivalent to

margin-top:0px
margin-right:auto;
margin-bottom:0px
margin-left:auto;

or

margin 0px auto 0px auto;

you should go for something like:

margin 30px auto 0px auto;

note that this only works with elements that have a set width. Also, you could use

    line-height: 'your div height' 

to align the text in the middle

LaughingMan
  • 640
  • 1
  • 9
  • 18
0

{width : auto; margin : auto} will work, you may need to fix the width of the element you to center

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
Vikash Kesarwani
  • 850
  • 5
  • 14
0

Just add the following to your CSS code:

text-align: center;
vertical-align: middle;
line-height: 400px; /* the same as your div height */

DEMO

azhpo
  • 764
  • 3
  • 7
  • 18
0

You can use absolute position, to center it on the page

#item {
    height:400px;
    width:700px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -200px;
    margin-left: -350px;
    background-color:white;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}
Ahmad
  • 8,811
  • 11
  • 76
  • 141
0

Create a div outside of this div and make its width 100%. Now give your div margin: 0 auto; with a position: relative. This should work.

<div style="width:100%">
  <div id="item"></div>
</div>
user1012181
  • 8,648
  • 10
  • 64
  • 106