How to centre a div and how to centre the contents of a div
1. I want to centre a DIV
2. I want to centre the contents of a DIV
I did a google and it seems this is not straight forward!
I came across several different answers
I'd be happy to go with one of the answer: but most of these are dated more than 5 years ago - I assumed that the code maybe old and outdated now?
Can someone give me a definitive answer to how to centre a DIV and separately, how to centre the contents of a DIV
To center a div you need to giv it a width and then set its left and right margins to auto.
This will centre the div inside its parent element.
margin: 0px auto 0px auto}
Centreing the div's content depends on what the content actually is.
If you can, maybe post your code or example content you want to centre.
To center horizontally a DIV is simple: give it a certain size and give it margin-left:auto and margin-right:auto.
Vertically, it is a more intricate job...but you have not mentioned if you need center vertically as well.
Regarding the second question: it depends on what do you mean by "contents of a DIV". If block elements, they are to be centered as above. If inline elements or text, give the DIV a text-align:center.
margin: 0 auto;
That all you need for the CSS. Make a selector name and set the id="" attribute in the div with the name. All widths must be less than 100% to center.
"text-align: center;" will center the text within the div container.
I disagree - if the content of the div includes child divs, images, tables floated, unfloated, css positioned or whatever then text-align: center on its own is not going to center the div contents.
Originally Posted by Major Payne
As mentioned earlier, we need to know what the contents are before they can be centred using css.
Need to re-read what I said. The text align only aligns the text. The main div will be centered and the contents, meaning the related text only, will be centered.
Originally Posted by tirna
When I said that's all there is, I was saying you don't need all the margin: 0 auto 0 auto; coding either. Any other divs inside the div that was being asked about is another matter as stated, but OP didn't asked about div containers inside of div containers. I like to stick to just what is asked without making things complex. If clarification is needed, then I will clarify or answer further questions about the subject.
...entire layout goes here...
Change text-align as needed.
margin: 0 auto;
Put all your page's content in "container" and use "position" (in CSS) to make it behave/appear where and how you want it to.
1) everything inside div
<div align="center"> </div>
2) For simple text:
<center> dddddddd </center>
3) for images or frames
<img style="display:block;margin-left:auto;margin-right:auto;" align="center" src="xx.jpg" />
Users Browsing this Thread
There are currently 2 users browsing this thread. (0 members and 2 guests)