1

Im trying to vertical center children of an absolute positioned div with no luck. Anyone having a good solution for this? (whitout js).

<div class="title">
    <div>
        <span>03</span>
    </div>
    <h2>
        title
    </h2>
</div>

css:

.title {
    height: 100%;
    position: absolute;
    text-align: center;
    width: 100%;
}

.title div,h2 {
    //i want to center these two verical
}
user2952238
  • 669
  • 2
  • 10
  • 33
  • That question provides you a lot of options just try and choose the one can suit your layout. – DaniP Nov 20 '14 at 12:22

3 Answers3

5

A modern way to go is like this (I recommend the extra div):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>

.title {
    height: 100%;
    position: absolute;
    text-align: center;
    width: 100%;
}

.title-inner {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

</style>
</head>
<body>

<div class="title">
    <div class="title-inner">
        <div>
            <span>03</span>
        </div>
        <h2>
            title
        </h2>
    </div>
</div>

</body>
</html>
ralph.m
  • 12,558
  • 3
  • 19
  • 29
0

For vertically align you have to use vertical-align:middle try this i think you want something like that ?

*
{
margin:0;
padding:0;
}
.title {
    height: 100%;
    position: absolute;
    text-align: center;
    width: 100%;
    display:table;
}

.vertically_algn {
    display:table-cell;
    vertical-align: middle;
}

http://jsfiddle.net/qe8suw58/

0

You can do it using display table and table-cell. They are good when you don't know the height and width of the elements that you want to align vertical middle :)

* {
  margin: 0px;
}
.title {
  height: 100%;
  position: absolute;
  text-align: center;
  width: 100%;
  background: red;
  display: table;
}
.aligner {
  display: table-cell;
  vertical-align: middle;
}
<div class="title">
  <div class="aligner">
    <div>
      <span>03</span>
    </div>
    <h2>
        title
    </h2>
  </div>
</div>
Bojan Petkovski
  • 6,503
  • 1
  • 19
  • 32