1

I wonder what's the best way to center a div horizontally only, basically it wouldn't matter the height only the width. I've seen so many examples around but they focused about horizontal and vertical alike, which I do not need neither want.

So lets say I have this:

<body>
<div id="layout">
    Content of my site here.
</div>
</body>
Jedediah
  • 1,916
  • 16
  • 32
GuyB790
  • 13
  • 3
  • Question title: "How to center a div vertically only?". Question body: "what's the best way to center a div horizontally only". Good luck with that. – thirtydot Sep 10 '13 at 17:54
  • You have asked two different questions. Your title asks for vertical alignment and your post asks for horizontal alignment. What do you want? – brbcoding Sep 10 '13 at 17:54
  • Search for `vertical align center` on SO, many answers such as http://stackoverflow.com/questions/11048541/vertical-text-center-in-div – Marc Audet Sep 10 '13 at 17:55

4 Answers4

1

Vertical:

For verticals, you must use something like:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

And just use this:

ul {
list-style: none;
margin: 0;
padding: 0;
}

This will remove paddings margins and list style. And you will have a vertical list. Now place it where you want!

Horizontal:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Now for this there is just one more line in CSS:

ul li {
display: inline; // this is used to place elements in one line..
}

Others will be same!

This is all! Now you can place this list in your div. And it will work!

To position it, you can either use position: absolute for this you will require to use position: relative for the parent div. Or you can use padding: or margin. That's all that you would require!

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
0
#layout {
    margin: 0 auto;
    position: relative;
}

That will center #layout horizontally relative to the window, or it's parent, if it has one.

Jedediah
  • 1,916
  • 16
  • 32
0

It will center vertically

  #layout{position:absolute;top:50%;margin-top:-heightofDiv/2;}
Voonic
  • 4,667
  • 3
  • 27
  • 58
0

Most appropriate way to do is using either

margin-top:
margin-bottom:

padding-top:
padding-bottom:

What to choose between margin and padding depends on your layout. In your code, you can choose margin applied to

 <div id="layout"> 

or else you can set padding of the container of the

 <div id="layout"> 

(body in this case).