I have always been wondering how other people get to align to the centre the main div container as the only way I manage so far is adding to the css file the following:
*{ padding:auto; margin:auto; text-align:centre; }
I have seen other pages using: *{padding:0px;margin:0px}
but I can't see where or what do they do to centralise the main container.
Could anybody explain how?
Code example:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=windows-1252" http-equiv="Content-Type" /> <title>This is the main container</title> <style type="text/css"> *{ padding:auto; margin:auto; text-align:center; } </style> </head> <body> <div style="width:400px;background-color:#66FFFF;display:block;height:400px;"> <b>This is the main container.</b> </div> </body> </html>
Could anybody explain how do they do it in the following page?
http://www.csszengarden.com/?cssfile=/179/179.css&page=4
By using flex layout model: Set the display of the parent div to display: flex; and the you can align the child elements inside the div using the justify-content: center; (to align the items on main axis) and align-items: center; (to align the items on cross axis).
You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left. Welcome to Stack Overflow =)
Do not use the *
selector as that will apply to all elements on the page. Suppose you have a structure like this:
... <body> <div id="content"> <b>This is the main container.</b> </div> </body> </html>
You can then center the #content
div using:
#content { width: 400px; margin: 0 auto; background-color: #66ffff; }
Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; }
snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.
Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With