onlineracoon
onlineracoon

Reputation: 2970

CSS centering text in parent with variable height

Look at the image below, it explains my question

So basically I need to center (vertically) text, but the height is variable, since it can be on multiple lines, how can I do this?

What I've tried:

.box {
  text-align: center;
  vertical-align: center;
}

.box {
  position: absolute;
  top: 50%;
  text-align: center;
  left: 50%;
}

.box {
  margin: 50% auto;
  text-align: center;
}

I don't know if this is even possible or if I have to correct it with JS.

Upvotes: 1

Views: 194

Answers (2)

Sowmya
Sowmya

Reputation: 26979

Use display:table-cell

.box {
  text-align: center;
  vertical-align: middle;
    background:black;
    color:white;
    height:200px;
    display:table-cell;
    width:450px
}

DEMO - Single line

DEMO - Multi line

Upvotes: 2

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

Here you go, works vertically and horizontally.

HTML:

<div class="area">
      <div class="bubble">
          <p>To look best, text should really be centered inside this bubble both vertically and horizontally.</p>
      </div>
</div>​

CSS:

   .area { 
      width: 300px; 
      height: 300px; 
      background: url(../images/abe-bg.png) no-repeat; 
      position: relative;
    }

    .bubble { 
      position: absolute; 
      left: 93px; 
      top: 21px; 
      width: 135px; 
      height: 84px; 
      display: table; 
    }

    .bubble p {
      display: table-cell; 
      vertical-align: middle; 
      text-align: center; 
    }​

DEMO

Upvotes: 1

Related Questions