Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I float a div to the center?

Tags:

I want to be able to center a div in the middle of a page but can't get it to work. I tried float: center; in css but it doesn't seem to work.

like image 783
Eli Reznekervitz Avatar asked Feb 13 '11 03:02

Eli Reznekervitz


People also ask

How do I force a div to center?

Simply add text-align center to parent div and set the child div display to inline-block. This will force our div to behave like inline element and therefore subjected text-align center.

How do you float an object to the center?

There is no way to float center in CSS layout. So, we can center the elements by using position property. Example 1: This example set the position of elements exactly at the center of the screen.


2 Answers

There is no float: center; in css. Use margin: 0 auto; instead. So like this:

.mydivclass {
    margin: 0 auto;
 }
like image 62
Drew Bartlett Avatar answered Oct 02 '22 07:10

Drew Bartlett


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*/
}
like image 34
Hussein Avatar answered Oct 02 '22 09:10

Hussein