Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

centering a div

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34410
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64837
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Set the left and right margins to auto, and give the <div> a width.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34410
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 173
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34410
346
Eclipse IDE Java VI Editor
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic