基础代码
<style>
html,body{
height: 100%;
width: 100%;
}
.box{
width: 100px;
height: 100px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
1.父级flex
加元素本身margin: auto
html,body{
display: flex;
}
.block{
margin: auto;
}
2.父级flex
html,body{
display: flex;
justify-content: center;
align-items: center;
}
3.定位
缺陷:需要知道盒子的宽高,但在自适应页面下无法做到
/* Codes/CSS/居中对齐/03.定位.html */
html,body{
position: relative;
}
.box{
position: absolute;
top:50%;
left:50%;
margin-left: -50px;
margin-top: -50px;
}
4.定位,但无须知道宽高
缺陷:盒子本身必须有宽高,否则失效
/* Codes/CSS/居中对齐/04.html */
html,body{
position: relative;
}
.box{
position: absolute;
top:0;
bottom: 0;
left:0;
right:0;
margin: auto;
}
5.定位+transform:translate
原理:transform: translate(-50%, -50%)
相当于自身向左、向下移动50%
优点:不需要宽高也可以居中,根据内容撑开盒子
缺陷:兼容性较差
/* Codes/CSS/居中对齐/05.html */
html,body{
height: 100%;
width: 100%;
position: relative;
}
.box{
position: absolute;
background-color: aquamarine;
top:50%;
left:50%;
transform: translate(-50%, -50%);
}
6.使用js
缺陷:直接操作DOM;需要盒子有宽高
<!-- Codes/CSS/居中对齐/06.html -->
<div class="box">fltenwall</div>
<script>
let HTML = document.documentElement,
winWidth = HTML.clientWidth,
winHeight = HTML.clientHeight
let Box = document.getElementsByClassName('box')[0]
BoxWidth = Box.offsetWidth,
BoxHight = Box.offsetHeight;
Box.style.position="absolute"
Box.style.left=(winWidth-BoxWidth)/2+'px'
Box.style.top=(winHeight-BoxHight)/2+'px'
</script>
7.利用table-cell
缺陷:奇淫技巧;父盒子必须有宽高
<!-- Codes/CSS/居中对齐/07.html -->
<style>
.father{
display: table-cell;
vertical-align: middle;
text-align: center;
width: 300px;
height: 300px;
background-color: bisque;
}
.box{
display: inline-block;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="father">
<div class="box">fltenwall</div>
</div>
</body>