Kyle Maclean
Kyle Maclean

Reputation: 81

Centring a div with left, right, and absolute positioning

I have a div with position:absolute and I need to get it in the centre of the document. What I thought would work is using left:50%; top:50%, but this moves the div 50% from the top and left according to its sides, so it's more to the right and bottom than I'd want. Is there a way to move the div using the centre of it as the focus point?

The height and width both have to be 300px and the div must always be in the centre of the document regardless of the resolution - which is why I can't use static values and have to use percentages

Upvotes: 0

Views: 9274

Answers (4)

user2211216
user2211216

Reputation: 375

why not try this, its simpler and more general than messing with pixels:

.div {
position:absolute;
border:1px solid black;
width:100px;
height:100px;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;

}

Upvotes: 5

Kyle Maclean
Kyle Maclean

Reputation: 81

user2211216 got what I wanted - just use

margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
position: absolute;

Upvotes: 0

NoobEditor
NoobEditor

Reputation: 15871

Based on Mr.Alien's fiddle, i would suggest you to use calc for exact middle alignment for fixed dimension width

The idea is to use calc(50% - 150px); i.e., (50% - half the dimension of the block)

This way, you can avoid the hacks of :

margin-left: -xxpx;
margin-top: -xxpx;

CSS

div {
    height: 300px;
    width: 300px;
    background: tomato;
    position: absolute;
    top: calc(50% - 150px);
    top: -moz-calc(50% - 150px);
    top: -webkit-calc(50% - 150px);
    left: calc(50% - 150px);
    left: -moz-calc(50% - 150px);
    left: -webkit-calc(50% - 150px);
}

working fiddle

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157314

I didn't understood what you meant by but this moves the document 50% from the top and left so you should target the div and not the container element.

Demo

div {
    height: 100px;
    width: 100px;
    background: tomato;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}

Above am using all the properties which you are using, but apart from that am using margin-left and margin-top with negative values which are equivalent to 1/2 of the elements height and width


Now that's the solution for a fixed width element, if your element width and height are variable, you will have to set your container element to display: table-cell; and than use vertical-align: middle; to align the element to vertically center, whereas margin: auto; will take care of the horizontally center alignment.

Demo


Note: Am using display: table; for body which is kinda dirty way, so consider using a wrapper element for that and then assign display: table-cell; to that, also, make sure you have see all the parent element height to 100%

Upvotes: 6

Related Questions