javascript - 更改屏幕尺寸时如何将文本保持在 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>
谢谢你的帮助。
解决方案
您可以使用 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>
推荐阅读
- python - 收到一封空白电子邮件
- php - 伙计们,那里的任何人都严重陷入了codeigniter 3路线
- ios - 如何使用swift中的自定义按钮选择tableview中的所有单元格?
- typescript - 为 DSL 扩展 TypeScript 编译器
- c# - 在 while 部分变为假 C# 后,Do-while 循环不会停止
- spring - 缺少肥皂动作 :: Spring 集成
- visual-studio-2017 - Visual C++ 中缺少视图设计 (Visual Studio 2017)
- google-apps-script - 搜索不同电子表格中的列
- dart - SpriteWidget:应用程序不响应 NodeWithSize 中的 handleEvent
- zend-framework3 - Zend Framework 3.0.3-dev 中的自动加载器