• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

centering a div

 
author & internet detective
Posts: 40198
816
Eclipse IDE VI Editor Java
  • 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.
 
Marshal
Posts: 67447
173
Mac Mac OS X IntelliJ IDE jQuery Java
  • 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
Posts: 40198
816
Eclipse IDE VI Editor Java
  • 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% }
 
author
Posts: 200
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
Posts: 40198
816
Eclipse IDE VI Editor Java
 
That feels good. Thanks. Here's a tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic