首页 > 解决方案 > 为什么文本居中时不显示我的文本?

问题描述

div文本居中时未显示我的文本。我div分配width给一个div.Text 应该next在线。

这是我的代码

body,html{
  width:100%;
  height:100%;
  background:blue
}
.centered {
  width:100%;
  height:100%;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align:center;
  background: red; /* not necessary just to see the result clearly */
}

.abc{
  background: #fff;
  width:200px;
  height:400px;
  line-height:400px;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div class="centered">
  <div class="abc">This text is centered horizontally and vertically</div>
</div>

</body>
</html>

标签: htmlcssflexbox

解决方案


导致问题的line height原因是,当您有换行符时,下一行将在之后,400px但您的 div 只是400px因此您​​将有溢出,因为内容的高度为800px(2 行)。改为删除line-height并应用 div 内的中心。Line-height对于仅居中一行文本很有用。

body,
html {
  width: 100%;
  height: 100%;
  margin:0;
  background: blue
}

.centered {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: red;/* not necessary just to see the result clearly */
}

.abc {
  background: #fff;
  width: 200px;
  height: 300px;
  display: flex;
  align-items: center;
    text-align:center;
}
<div class="centered">
  <div class="abc">This text is centered horizontally and vertically</div>
</div>


推荐阅读