2

I am new to css3. Just wanted to know how to center align a div, it should work on web browser, web-kit. I don't have the exact size of the page. I tried

div.inputs { 
   margin-left:auto;
   margin-right:auto;
}

But this never works for me.

dg99
  • 5,456
  • 3
  • 37
  • 49
chetank
  • 392
  • 3
  • 17

5 Answers5

3

Depending on your HTML you could use display: flex to achieve an easy completely centred element with a small amount of CSS and no additional HTML elements

.container{
    display: flex;
    align-items: center;
    justify-content: center;
}

Here is an example Fiddle

skii
  • 71
  • 1
  • 4
1

The best way is to define the width, and then set margin to auto & 0:

div.inputs{ margin: 0 auto; width 100%}

Fiddle

Phlume
  • 3,075
  • 2
  • 19
  • 38
  • even after having a width the div still remains at the top. is it because it is nested under two divs and that is causing the issue? – chetank Apr 17 '15 at 19:44
  • @chetank your comment "remains at the top" makes it sound like you want to VERTICALLY align, even though your example is referencing horizontal alignment... – ganders Apr 17 '15 at 19:49
  • @ganders i want the div to be centered, horizontally or vertically. I am not sure what might be the condition but my html is comething like this
    – chetank Apr 17 '15 at 20:00
  • 2
    if you don't know which you want... how can we answer? – Phlume Apr 17 '15 at 20:01
1

If you don't know the size of your element, you can use the display: inline-block; with a parent having text-align: center; or you can use a display: table; margin-left: auto; margin-right: auto;

romuleald
  • 1,406
  • 16
  • 31
0

Horizontally & Vertically:

Stable Solution (supports flexible height easily):

A more stable code could be look like this which works for vertically & horizontally center a fixed-width, flexible height content:

.outer {
  display: table;
  position: absolute;
  height: 100%;
  width: 100%;
}
.middle {
  display: table-cell;
  vertical-align: middle;
}
.inner {
  margin-left: auto;
  margin-right: auto;
  width: 100px
  /*whatever width you want*/
  ;
}
<div class="outer">
  <div class="middle">
    <div class="inner">

      <h1>The Content</h1>

      <p>The inner content :)</p>

    </div>
  </div>
</div>

Quick and dirty:

According to your comment on another answer you want it to be centered horizontally and vertically or only horizontally. You can do this by using position absolute:

.centerDiv {
    width:270px;
    height:150px;
    position:absolute;
    left:50%;
    top:50%;
    margin:-75px 0 0 -135px;
    
    background-color: green;
}
<div class="centerDiv">Center Me :)</div>

Only horizontally:

If you want it to be centered only horizontally simply use:

.centerDiv {
    width: 270px;
    margin: 0 auto;
}
DominikAngerer
  • 6,354
  • 5
  • 33
  • 60
0

See my answer on this Link here I used just div and span tag to center a div

Community
  • 1
  • 1
amachree tamunoemi
  • 817
  • 2
  • 16
  • 33