Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text needs in exact center Horizontally and vertically [duplicate]

Tags:

html

css

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/

like image 717
Husen Avatar asked Jul 02 '14 08:07

Husen


2 Answers

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

like image 192
Alex Char Avatar answered Oct 04 '22 23:10

Alex Char


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 :)

like image 41
user2969135 Avatar answered Oct 04 '22 22:10

user2969135