-1

Could anyone tell me how i would get this div to be centred at the top of the screen, with equal distances from the bounds of the page on both the left and the right.

position:relative;
width:800px;
height:70px;
background-color:#0CF;
left: 15%;

Thanks!

Callum
  • 932
  • 2
  • 8
  • 12

6 Answers6

2

By specifying automatic margins for left and right edges:

margin:0 auto;

This forces the browser to equalize them within the parent, which has full browser width, so it's centered since you have explicitly set the width.

Sample implementation.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
0

Well it depends on the parent element, and why you have it as position:relative;, but generally to center a block level element with a set width, within it's parent, you can just use:

margin:0 auto
MasNotsram
  • 2,105
  • 18
  • 28
0

Since you have a width set, you should use

margin:0 auto;
lazyprogrammer
  • 633
  • 9
  • 26
0

You should try this jsfiddle :

HTML :

<div>This is some DIV</div>

CSS :

div {
    width : 50%;
    margin : auto;
    border : 1px solid black; // To see that it is centered
}
Xaltar
  • 1,688
  • 14
  • 22
0

Usually when doing this you want to do something like below. It will stay withing the bounds of it's parent element and wherever you put it on the page but will place it in the middle.

If you want to put it in the code: style=" margin-left:auto; margin-right:auto;"

Otherwise just add that to your css for the div.

using this method will not set your upper and lower margin to auto.

0

use margin: 0 auto;

0 - stands for 0px top and bottom sides of the page auto - means it'll adjust itself according to the available window size and can make it center.