How do I float a div to the center?
I want to be able to center a div in the middle of a page but can'开发者_JS百科t get it to work. I tried float: center; in css but it doesn't seem to work.
There is no float: center; in css. Use margin: 0 auto; instead. So like this:
.mydivclass {
margin: 0 auto;
}
You can do it inline like this
<div style="margin:0px auto"></div>
or you can do it via class
<div class="x"><div>
in your css file or between <style></style>
add this .x{margin:0px auto}
or you can simply use the center tag
<center>
<div></div>
</center>
or if you using absolute position, you can do
.x{
width: 140px;
position: absolute;
top: 0px;
left: 50%;
margin-left: -70px; /*half the size of width*/
}
Try margin: 0 auto
, the div will need a fixed with.
If for some reason you have position absolute on the div, do this:
<div class="something"></div>
.something {
position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;
}
if you are using width
and height
, you should try margin-right: 45%;
... it is 100% working for me.. so i can take it to anywhere with percentage!
Give the DIV a specific with in percentage or pixels and center it using CSS margin property.
HTML
<div id="my-main-div"></div>
CSS
#my-main-div { margin: 0 auto; }
enjoy :)
Simple solution:
<style>
.center {
margin: auto;
}
</style>
<div class="center">
<p> somthing goes here </p>
</div>
Try Online
精彩评论