元素居中问题(横向&纵向)
参考:CSS实现垂直居中的常用方法
参考:父元素高度为auto:子元素使用top:-50%没有效果的问题
w3c的文档说
The offset is a percentage of the containing block’s width (for ‘left’ or ‘right’) or height (for ‘top’ and ‘bottom’). For ‘top’ and ‘bottom’, if the height of the containing block is not specified explicitly (i.e., it depends on content height), the percentage value is interpreted like ‘auto’.
如果父元素的高度没有明确指定,top 的值跟设定为auto的效果是一样的 。
即:若设相对长度%,外层父元素必须要有高度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>flex 居中</title>
<style>
* {
margin: 0;
padding: 0;
}
html,body {
/* 外层环境要有高度才有作用 */
height: 100%;
width: 100%;
display: flex;
/* 主轴方向居中 */
justify-content: center;
/* 交叉轴方向居中 */
align-items: center;
}
.bigbox {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
border: 10px ridge red;
/* --------常用老方法如下注释:-------- */
/* margin: 0 auto; */
/* position: relative;
top: 50%;
偏移自身高度的一半:
transform: translateY(-50%); */
}
.smallbox {
text-align: center;
line-height: 100px;
border: 1px solid #000;
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<div class="bigbox">
<div class="smallbox">够不够居中</div>
<div class="smallbox">文字如何</div>
</div>
</body>
</html>
如图: