File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes HTML, CSS and JavaScript and the fly likes centering a div Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "centering a div" Watch "centering a div" New topic
Author

centering a div

Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30085
    
149

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: 60774
    
  65

Set the left and right margins to auto, and give the <div> a width.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30085
    
149

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: 173
    
    6
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 JavaScript Programming
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30085
    
149

I see. Thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: centering a div
 
Similar Threads
How would be the best way to parse HTML Content ?
how to get HTML div id name from RootPanel
request.setAttribute() and request.getAttribute()
float property is not working properly
How to refresh a table in Struts