| Author |
centering a div
|
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26201
|
|
It's easy to center text within a div. To center the actual div, I still find myself typing:
Clearly not the HTML 5 way. Is there a better simple way to do this? Everything I've seen is quite complex. I understand it will be more complex/longer than the original. However, being very long/complex feels like a deterrent to writing HTML 5 compliant code.
|
[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56221
|
|
|
Set the left and right margins to auto, and give the <div> a width.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26201
|
|
That works, but I don't understand why.
# shows it about a third in
div.center50 { margin: auto; width: 50% }
# shows it just short of center. maybe 40 percent in
div.center50 { margin: auto; width: 10% }
# shows it exactly centered
div.center50 { margin: auto; width: 0% }
|
 |
Elisabeth Robson
author
Ranch Hand
Joined: May 14, 2004
Posts: 129
|
|
The reason to do it in CSS is to keep presentation and content separate.
In the first rule you have, you're setting the width of the div to 50%, which means 50% of the width of the viewport. By setting margin to auto, you're saying, let the browser decide what the margin should be. In most browsers, the behavior is to set the margin so it's equal on both sides of the div.
|
Co-Author of Head First HTML5 Programming
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26201
|
|
|
I see. Thanks.
|
 |
 |
|
|
subject: centering a div
|
|
|