Centering elements in a web page is probably one of the most common tasks for CSS.
There are three kinds of centering:
- Centering lines of text.
- Centering a block of text or an image.
- Centering a block or an image vertically.
text-align
property, to which apply the value: center
.<style> h3 { border: 1px solid blue; text-align: center; } #idiv { border: 1px dashed green; text-align: center; } </style> <h4>Example center text</h4> <h3>Free Wweb Programming Courses - coursesweb.net</h3> <div id='idiv'>Div with text centered.</div>
<style> #idiv { margin-left: auto; margin-right: auto; width: 200px; border: 2px dashed blue; padding: 5px; } </style> <h4>Example </h4> <div id='idiv'>Div centered. The lines inside the block are not centered (they are left-aligned).</div>
display:block;
property) and apply the margin properties to it. For example:
<style> #idimg { display: block; margin-left: auto; margin-right: auto; border: none; } </style> <h4>Example center image</h4> <div> Some text or other content... <img src='css/css3.jpg' alt='Text for image' width='200' height='100' id='idimg' /> </div>
vertical-align: middle;
, then the trick is to specify that this parent block is formatted as a table cell (with display: table-cell;
), because the contents of a table cell can be centered vertically.<style> div.container { height: 200px; border: 3px dotted blue; display: table-cell; /* forms as a table cell */ vertical-align: middle; padding: 3px 4px; } </style> <h4>Example center paragraph vertically</h4> <div class='container'> <p> This paragraph is vertically centered.<br> CSS Course: https://coursesweb.net/css </p> </div>
<style> div.container { height: 250px; border: 3px dotted blue; display: table-cell; /* forms as a table cell */ vertical-align: middle; /* center vertically */ text-align: center; /* center horizontally */ padding: 3px 4px; } </style> <h4>Example center image vertically</h4> <div class='container'> <img src='css/css3.jpg' alt='Text for image' width='170' height='100' /><br> This line of text and the image above are vertically and horizontally centered. </div>
<table><tr> <th>Title 1</th> <th>Title 2</th> </tr></table>
.some_class { line-height: 150%; }
document.getElementById("id_button").onclick = function(){ window.open("http://coursesweb.net/"); }
$ar_dir = scandir("dir_name"); var_export($ar_dir);