html - 为什么我的文字在居中时不显示?

标签 html css flexbox

我的 div 文本在我的 div 文本居中时没有显示。我将 width 分配给 div。文本应该出现在 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>

最佳答案

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>

关于html - 为什么我的文字在居中时不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868150/

相关文章:

python - 如何使用 BeautifulSoup 从相对网站路径获取完整网站路径

html - 如果 CSS flexbox 中的最后一行,则在第一行中填充剩余宽度

html - 3 列 Flex 布局 - 中间列的宽度与其内容相同

html - 什么相当于 moz-box-orient?

c# - Silverlight 而非 WPF 中嵌套样式(如 CSS)的挂件

html - CSS 否定伪类 :not() for parent/ancestor elements

javascript - 从多个选定下拉列表的数据属性中获取值(动态下拉列表)

javascript - 同时沙盒和添加 JS/HTML 到 iFrame

jquery - 新手 jQuery 祖先导航问题

asp.net - 如何使用主页在事件菜单项上设置 css 类?