• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

centering a div

 
author & internet detective
Posts: 41878
909
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 67747
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Set the left and right margins to auto, and give the <div> a width.
 
Jeanne Boyarsky
author & internet detective
Posts: 41878
909
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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% }
 
author
Posts: 200
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 41878
909
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I see. Thanks.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic