0

I have a div that has a certain width and height. In that div I also have a text. I want to align that text to the center (horizontally) and to the middle (vertically). But the div also needs a position: absolute. So it can be positioned inside another div.

But because of the absolute the text won't align vertically anymore.

This is what I have:

<div style="z-index:20;
    position: absolute;
    border: 1px dotted #16232d;
    width: 300px;
    height: 200px;
    line-height: 200px;
    top:88px; left:31px;
    display: table-cell;
    line-height: normal;
    font-size:32px;
    text-align: center;
    vertical-align: middle;">
   Lorem ipsum dolor sit amet
</div>

Example: http://jsfiddle.net/s8jp5ohh/

The text will never contain any <br>. So it's always one line. But it should automatically break to a new line when the text is larger than the width of the div. So I'd like to keep that functionality (like you can see in the fiddle).

Is there a way to align the text in the center, vertically and horizontally?

Vivendi
  • 20,047
  • 25
  • 121
  • 196
  • 1
    This has been answered before http://stackoverflow.com/questions/2939914/vertically-align-text-in-a-div – chargarg Aug 25 '14 at 20:54
  • What you want can not be accomplished with css alone. Closest thing you can come to it is have a wrapper to display:table and your div to display:table-cell. The vertical alignment will work, as will the horizontal one. – Radu Andrei Aug 25 '14 at 20:56

2 Answers2

4

This will solve it : DEMO

css

.myDiv {
    z-index:20;
    position: absolute;
    border: 1px dotted #16232d;
    width: 300px;
    height: 200px;
    top:88px;
    left:31px;
    line-height: normal;
    font-size:32px;
    text-align: center;
    display: table;
}
.myDiv p {
    display: table-cell;
    vertical-align: middle;
}

html

<div class="myDiv">
    <p>Lorem ipsum dolor </p>
</div>
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
0

You have to use a hack, but it works:

JSFiddle.

HTML

<div class="block" style="z-index:20;
position: absolute;
border: 1px dotted #16232d;
width: 300px;
height: 200px;
line-height: 200px;
top:88px; left:31px;
display: table-cell;
line-height: normal;
font-size:32px;
text-align: center;
vertical-align: middle;">
    <p style="vertical-align: middle; display: inline-block;"> Lorem ipsum dolor sit    amet</p>

CSS:

.block:before {
    content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em;
}
Alex
  • 4,674
  • 5
  • 38
  • 59