3

This is MY demo Work in JSFIDDLE

NB without using table property

http://jsfiddle.net/SxxWV/12/

I want to make the class .box should be vertically centered

CSS

.main{ height:300px; border:1px red solid;position:relative}
.box{width:40px; height:40px; background:red; }

/* for centering */
.box{ display: inline-block;position:relative; top:50% }
.main{ text-align: center; }

HTML

<div class="main">

 <div class="box"></div>   
</div>

4 Answers4

5

You need to subtract half of the height of the element you want to center, so in this case add the following to .box:

margin-top: -20px;
spiel
  • 347
  • 3
  • 15
1

I will Prefer to use CSS after

This line of CSS will work fine

.main:after{ content: ""; display: inline-block; 
height: 100%; vertical-align: middle; }

Here id the Demo Work

Dinesh Kanivu
  • 2,551
  • 1
  • 23
  • 55
0

You can set the box to position: absolute and then set the top and bottom to 0, and then set the margin to auto:

.box {
   position: absolute;
   top: 0;
   bottom: 0;
   margin: auto;
}

Here's an example:

http://jsfiddle.net/SxxWV/23/

TheYaXxE
  • 4,196
  • 3
  • 22
  • 34
0

You can try this :

Fiddle here

.main{ height:300px; border:1px red solid;position:relative}
.box{width:40px; height:40px; background:red; }

/* for centering */
.box{ display: inline-block;position:relative; top:50%; margin-top:-20px; }
.main{ text-align: center; }

Good Luck

Pradeep Pansari
  • 1,287
  • 6
  • 10