margin:auto; isn't working usually

mVaillette

New Member
Why would this be? The margin property works fine if I set an absolute value, such as 40px,

but when I use margin:auto it just ignores that. I got it to work on an element after trying a billion things and I still don't understand why it worked or failed to work.

Frustrated.
 

Absolution

New Member
If you can show the page which it is giving a problem it might help. I dont know for sure, but it may help if you set

display: block;

or

display: inline-block;
 

mVaillette

New Member
Here's a simplified example of what's bugging me:

.container behaves as it should, with its max-width and margin:auto; working properly. When the browser viewport gets too big it centers. However, the h1, h2 tags do not center.

HTML:
#header {
	background:#000;
}
h1,h2 {
	color:#FFF;
        margin:auto;
}
.container {
	max-width:960px;
	margin:auto;
}
HTML:
<body>
<div id="header">
	<div class="container">
    	<h1>Site title</h1>
        <h2>Clever tagline</h2>
    </div>
</div>
</body>

setting to display:block or display:inline-block; did nothing :(
 

ronaldroe

Super Moderator
Staff member
You haven't set a width. Auto margins don't work without width declarations, and max-width doesn't count.
 

mVaillette

New Member
Oh. That's annoying. So I need to know the width/height of a block of text in order to margin:auto it, huh?

*folds arms*

Is there a trick to this? or is it just unnecessarily annoying?

Thanks a lot for the replies guys :)
 

PixelPusher

Super Moderator
Staff member
You haven't set a width. Auto margins don't work without width declarations, and max-width doesn't count.

Bingo!

Try:

text-align: center;

Exactly. If you want to use margin auto on a heading element, this leads me to believe that you want it centered, hence why worry about the margin property when you have a text-align property that will solve the issue more semantically.
 

mVaillette

New Member
thanks guys. Text align worked. Setting a width worked too.

What are some good tutorials or books that you can recommend I go through that would tell me about a lot of the common problems?

I'm ripping my hair out again on margin:0 auto; not working (I'm doing something else).

It always works when I am doing something simple like centering a #wrapper, but doesn't usually work when trying to center an element inside of a div container.
 
Top