首页 > 解决方案 > 更改屏幕尺寸时如何将文本保持在 html 部分的中心?

问题描述

我已经实现了一个包含 2 个部分的简单网页。在本节的每个部分中,都有包含 2 行的文本。在更改屏幕尺寸 (RWD) 时,我想将此文本保持在该部分的中心(左、上、右、下边距)。例如,当我在桌面上运行此网页时,该部分中的文本将位于该部分的中心,当我在智能手机/平板电脑上运行此网页时,该文本也位于该部分的中心。有可能做到吗?代码如下:

body {
  height: 100%;
}
section {
  height: 60vh;
}
section:nth-child(1) {
  background: white;
}
section:nth-child(2) {
  background: #f2efef;
}
 <!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

  <section>
    John is happy.<br><br>
    Thank you.<br><br>
  </section>

  <section>
    Have a nice day.<br><br>
    Good luck.<br><br>
  </section>

</body>
</html>

谢谢你的帮助。

标签: javascripthtmlcsscenter

解决方案


您可以使用 flexbox 网格进行块对齐。

body {
  height: 100%;
}
section {
  height: 60vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
section:nth-child(1) {
  background: white;
}
section:nth-child(2) {
  background: #f2efef;
}
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

  <section>
    John is happy.<br><br>
    Thank you.<br><br>
  </section>

  <section>
    Have a nice day.<br><br>
    Good luck.<br><br>
  </section>

</body>
</html>


推荐阅读