width and center css code example

Example 1: css center position

/**************** 1º method to center all elements ********************/
body {                   
  text-align: center;
}

/* If all of your elements have the property display equal to "inline", 
"block" or "inline-block", then you can use the text-align: center in
the <body> tag */

tag_name {
    display: inline; /* block or inline-block*/
}

/*...but if we have an element of type "block" with a width diferente
from the default (maximum width of the page), then this will no 
longer work!*/
  
tag_name {
    display: block;
  	width: 170px;
}


/**************** 2º method to center all elements ********************/
/* Another method, is to use the margins to center the element 
horizontally and/or vertically */

tag_name {
    display: block;
  	width: 100px;
  	margin: 0 auto 0 auto;  /* top, right, bottom, left */
}

Example 2: how to center div

<!--center text-->
<!--padding deals with margins within the element itself-->
<!--margin deals with blank space surrounding and element-->
<!DOCTYPE html>
<html>
<head>
<style>
.center {
  margin: auto;
  width: 80%;
  border: 3px solid #73AD21;
  padding: 10px; 
  margin: 20px;
}
</style>
</head>
<body>

<h2>Center Align Elements</h2>
<p>To horizontally center a block element (like div), use margin: auto;</p>

<div class="center">
  <p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p>
</div>

</body>
</html>

Tags:

Css Example