This question already has an answer here:
- How to horizontally center a <div>? 93 answers
I'm trying to horizontally center a <div>
block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div>
element to be inline with rest of my page. I'll try to draw an example:
page text page text page text page text
page text page text page text page text
-------
| div |
-------
page text page text page text page text
page text page text page text page text
In your html file you write:
your css file you write:
works for me.
In most browsers this will work:
In IE6 you will need to add another outer
div
:After nine years I thought it was time to bring a new version. Here are my two (and now one) favourites.
Margin
Set
margin
toauto
. You should know the direction sequence ismargin: *top* *right* *bottom* *left*;
ormargin: *top&bottom* *left&right*
Center: Depricated, don't use this!
Use
<center></center>
tags as a wrap around your<div></div>
.Example:
In the case of a non-fixed width div (i.e. you don't know how much space the div will occupy).
Keep in mind that the width of
#yourdiv
is dynamic -> it will grow and shrink to accommodate the text inside it.You can check browser compatibility on Caniuse
Please use below code your div will be in center
}
The title of the question and the content is actually different, so I will post two solutions for that using
Flexbox
.I guess
Flexbox
will replace/add to the current standard solution by the time IE8 and IE9 is completely destroyed ;)Check the current Browser compatibility table for flexbox
Single element
Multiple elements but center only one
Default behaviour is
flex-direction: row
which will align all the child items in a single line. Setting it toflex-direction: column
will help the lines to be stacked.