一、CSS 如何实现盒子水平垂直居中?
-
参考资料
zhuanlan.zhihu.com/p/160929003…
-
常用两种
方法一:子绝父相 (适用于子盒子有宽度和高度的时候)
.parent {
width: 200px;
height: 200px;
border: 1px solid #000000;
position: relative;
}
.child {
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: #00FFFF;
}
方法二:flex布局(子盒子有或没有宽高的时候都适用)
.parent {
width: 200px;
height: 200px;
border: 1px solid #000000;
display: flex;
justify-content: center;/* 水平居中 */
align-items: center;/* 垂直居中 */
}
.child {
width: 100px;
height: 100px;
background: #00FFFF;
}
特别说明:让块级元素水平居中的margin方法
margin:0 auto; 只能设置水平居中
而margin:auto 0; 不能设置垂直居中,因为margin垂直塌陷问题
二、CSS 如何实现行内元素(例如文本内容)水平垂直居中?
-
参考资料
-
总结收获
情况一:单行文本垂直居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css单行文本水平垂直居中</title>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid #000000;
text-align: center;/* 设置文本水平居中 */
line-height: 200px;/* 设置line-height与父级元素的height相等实现文本垂直居中 */
overflow: hidden;/*防止内容超出容器或者产生自动换行*/
font-size: 22px;
font-family: 楷体;/* 设置字体大小和样式 */
}
img {
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div class="box">
<sapn>我想要贩卖</sapn>
<img src="./sun.jpg" alt="pic">
</div>
</body>
</html>
情况二:多行文本垂直居中(父级元素高度不固定)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css多行文本水平垂直居中1</title>
<style>
.box {
width: 200px;
border: 1px solid red;
text-align: center; /*设置文本水平居中*/
padding: 50px 20px;/*通过内边距将盒子撑大实现居中,上下左右的值可以一样,或者上下一样左右一样*/
}
</style>
</head>
<body>
<div class="box">
这是多行文本垂直居中,
这是多行文本垂直居中,
这是多行文本垂直居中,
这是多行文本垂直居中。
</div>
</body>
</html>
情况三:多行文本垂直居中(父级元素高度固定)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css多行文本水平垂直居中2</title>
<style>
.box {
width: 200px;
height: 200px;
border: 1px solid red;
text-align: center;/*设置文本水平居中*/
line-height: 200px;/*设置文本垂直居中*/
}
span {
display: inline-block;
vertical-align: middle;
line-height: 22px;
}
</style>
</head>
<body>
<div class="box">
<span>测试文字 <br /> 测试文字<br /> 测试文字<br /> 测试文字<br /> 测试文字<br /> 测试文字</span>
</div>
</body>
</html>