5

I need to create something like: Text should come in exact middle position horizontally and vertically. I've achieve horizontally, but having problem in vertically. As, my text is dynamic. Sometime it is two line of text , sometime its four line or sometimes its only one line.

Here is my CSS CODE:

.image-container { border:1px solid #CCC; height:300px; width:300px; position:relative; float:left; margin-left:20px; }
p {position:absolute; top:40%; text-align:center; width:100%; }

Here is a html :

 <div class="image-container">
<p> One line Content works perfact</p>
 </div>
 <div class="image-container">
<p> Two line Content:Lorem Ipsum is simply dummy text of the printing </p>
 </div>
 <div class="image-container">
<p> Three Line Content:Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
 </div>

Please find the fiddle link : http://jsfiddle.net/YK7V5/

Husen
  • 955
  • 1
  • 6
  • 16

2 Answers2

7

I suggest to go with display:table and display:table-cell technique:

css

.image-container{
  display:table;
  border:1px solid #CCC; 
  height:300px; 
  width:300px; 
  position:relative;
  float:left;
  margin-left:20px;
 }
p {
 display:table-cell;
 text-align:center;
 width:100%;
 vertical-align: middle;
}

fiddle

Also take a look here:

6 Methods For Vertical Centering With CSS

Alex Char
  • 32,879
  • 9
  • 49
  • 70
3

Hey tested this in you fiddle and it works :)

.image-container { border:1px solid #CCC; height:300px; width:300px; position:relative; float:left; margin-left:20px; }
    p {text-align:center; display: table-cell; vertical-align: middle; height: 300px; width: 300px;}

Hope it works for you :)