首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在div中居中和垂直对齐文本?

如何在div中居中和垂直对齐文本?
EN

Stack Overflow用户
提问于 2016-05-24 23:18:01
回答 2查看 13.6K关注 0票数 1

下面的代码可以很好地垂直对齐div中的文本,但当我尝试将其居中时,只有需要换行的文本才会居中。当文本很短时,比如5-6个单词,文本就不居中。我不知道是因为我,还是我做错了什么。

我正在使用display: table-cell;进行垂直对齐。divp元素在CSS中以相同的方式定义。查看代码以了解问题所在。

代码语言:javascript
复制
<style>
  .outer { outline: 1px solid #eee; }
  .outer > p { 
    display: table-cell; 
    height: 200px; 
    vertical-align: middle;
    text-align: center;
  }
</style>
<div class="outer">
  <p>
    This longer text will be vertically aligned.
  </p>
</div>
<div class="outer">
  <p>
    This longer text will be vertically aligned and centered. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>

http://codepen.io/anon/pen/vGowKL

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-24 23:44:50

您只需要将包装outer类声明为display: tablewidth: 100%...您已经将孩子的p设置为display: table-cell。更新代码:http://codepen.io/anon/pen/VaoOJp

代码语言:javascript
复制
.outer { 
  outline: 1px solid #eee; 
  display: table; 
  width: 100%;
}
.outer > p { 
  display: table-cell; 
  height: 200px; 
  vertical-align: middle;
  text-align: center;
}
代码语言:javascript
复制
<div class="outer">
  <p>
    This longer text will be vertically aligned.
  </p>
</div>
<div class="outer">
  <p>
    This longer text will be vertically aligned and centered. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>

票数 4
EN

Stack Overflow用户

发布于 2016-05-24 23:30:37

代码语言:javascript
复制
.outer >p { 
 display: flex;
 height: 100%;
justify-content: center;
 align-items: center;
}

您可以使用flexbox来简化操作。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37417673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档