Vertically center text with CSS

2018-12-30 22:01发布

I have a div element which contains text, and I want to align the contents of this div vertically center.

Here is my div style:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

What is the best way to do this?

30条回答
ら面具成の殇う
2楼-- · 2018-12-30 22:35

You can also use below properties.

display: flex; 
align-content: center; 
justify-content : center;
查看更多
柔情千种
3楼-- · 2018-12-30 22:35

Even better idea for this. You can do like this too

body,
html {
  height: 100%;
}

.parent {
  white-space: nowrap;
  height: 100%;
  text-align: center;
}

.parent:after {
  display: inline-block;
  vertical-align: middle;
  height: 100%;
  content: '';
}

.centered {
  display: inline-block;
  vertical-align: middle;
  white-space: normal;
}
<div class="parent">
  <div class="centered">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
</div>

查看更多
只若初见
4楼-- · 2018-12-30 22:35

For a single line of text (or a single character) you can use this technique:

It can be used when #box has non-fixed, relative height in %.

<div id="box"></div>

#box::before {
    display: block;
    content: "";
    height: 50%;
}

#box::after {
    vertical-align: top;
    line-height: 0;
    content: "TextContent";
}

See live demo at JsBin (easier to edit CSS) or JsFiddle (easier to change height of result frame).

If you want to place inner text in HTML, not in CSS, then you need to wrap text content in additional inline element and edit #box::after to match it. (And, of course, content: property should be removed.)
For example,
<div id="box"><span>TextContent</span></div>
In this case #box::after should be replaced to #box span.

For IE8 support you must replace :: with :.

查看更多
美炸的是我
5楼-- · 2018-12-30 22:35

A very simple & most powerful solution to vertically align center:

.outer-div {
  height: 200px;
  width: 200px;
  text-align: center;
  border: 1px solid #000;
}

.inner {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  color: red;
}
<div class="outer-div">
  <span class="inner">No data available</span>
</div>

查看更多
长期被迫恋爱
6楼-- · 2018-12-30 22:37

Set it within button instead of div if you don't care about its little visual 3D effect.

#box
{
  height: 120px;
  width: 300px;
  background: #000;
  font-size: 48px;
  font-style: oblique;
  color: #FFF;
}
<button Id="box" disabled>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</button>

查看更多
看淡一切
7楼-- · 2018-12-30 22:38

You can use the positioning method in CSS:

Check the result here....

HTML:

<div class="relativediv">
  <p>
    Make me vertical align as center
  </p>
</div>

CSS:

.relativediv{position:relative;border:1px solid #ffffd;height:300px;width:300px}
.relativediv p{position:absolute:top:50%;transfrom:translateY(-50%);}

Hope you use this method too.

查看更多
登录 后发表回答