Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS absolute position won't work with margin-left:auto margin-right: auto

Tags:

html

css

position

Say you have the following CSS applied to a div tag

.divtagABS {     position: absolute;     margin-left: auto;       margin-right: auto; } 

the margin-left and margin-right does not take effect

but if you have relative, it works fine i.e.

.divtagREL {     position: relative;     margin-left: auto;       margin-right: auto; } 

Why is that? I just want to center an element.

Can someone explain why setting margins to auto in absolute position does not work?

like image 471
user1118019 Avatar asked Apr 03 '12 17:04

user1118019


People also ask

Does margin auto work with position absolute?

"An element with position absolute cannot be centered..." Actually, this is not true: The key is to set all top/bottom/left/right properties to 0 and declare width and height , then margin: auto will automatically center the absolutely positioned element.

Why is margin auto not working CSS?

margin:auto won't work when you have a float or haven't specified a width. kohoutek: margin:auto won't work when you have a float or haven't specified a width.

Why margin 0 Auto does not work?

First things first, each of the elements above are blocks and have set margin: 0 auto, but it does not work since blocks have width equal to 100% by default (the first example). The block covers the whole page and therefore cannot be centered.

What effect does happen on a element if left and right margin is given Auto Value?

By assigning auto to the left and right margins of an element, they take up the available horizontal space in the element's container equally – and thus the element gets centered.


2 Answers

EDIT : this answer used to claim that it isn't possible to center an absolutely positioned element with margin: auto;, but this simply isn't true. Because this is the most up-voted and accepted answer, I guessed I'd just change it to be correct.

When you apply the following CSS to an element

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

And then give the element a fixed width and height, such as 200px or 40%, the element will center itself.

Here's a Fiddle that demonstrates the effect.

like image 146
Kevin Bowersox Avatar answered Sep 20 '22 13:09

Kevin Bowersox


I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.

.divtagABS {     width: 100px;     position: absolute;     left: 50%;     margin-left: -50px;   } 

Basically, you use left: 50%, then back it out half of it's width with a negative margin.

like image 34
chipcullen Avatar answered Sep 22 '22 13:09

chipcullen