Setting the width of a block-level element will prevent it from stretching out to the edges of its container. Use margin: auto;, to horizontally center an element within its container. The element will then take up the specified width, and the remaining space will be split equally between the two margins:
HTML file: | Displayed by browser: |
---|---|
<style>
.center { margin: auto; width: 60%; border: 3px solid #8AC007; padding: 10px; } </style> <body> <div class="center"> <p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p> </div> </body> |
Note: Using margin:auto will not work in IE8, unless a !DOCTYPE is declared. |
Tip: Center aligning has no effect if the width property is not set (or set to 100%). For aligning text, see the Text Alignment chapter.