版权声明:如有雷同,纯属巧合!!! https://blog.csdn.net/COCOLI_BK/article/details/85346102
本篇将学习到以下知识点:
-
盒子水平竖直居中的方式
盒子水平竖直居中的方式
方法1:子盒子宽度和高度已知的。
思路:
给父元素相对定位
给子元素绝对定位
left: 50%;top: 50%;
margin-left: 负的宽度一半。
margin-top: 负的高度一半;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>盒子水平垂直居中</title>
<style>
/*
*宽高已知的盒子
*子绝对定位,父相对定位
*margin盒子一半的负值
*/
.parent{
position: relative;
width: 400px;
height: 400px;
margin:0 auto;
background-color: aqua;
}
.child{
position: absolute;
width: 100px;
height: 100px;
background-color: blueviolet;
left: 50%;
top:50%;
/* 主要代码 */
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">dsaf</div>
</div>
</body>
</html>
方法2:子盒子宽度和高度未知的。
是说子盒子本身还是有宽度和高度的,只是自己未知。
思路:
给父盒子相对定位 ;
给子盒子绝对定位
top、right、bottom、left全为0
margin: auto;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>盒子居中</title>
<style>
/*
*宽高未知的盒子
*子绝对定位,父相对定位
*同时子元素样式里加:
*top:0; left:0; bottom:0; right:0; margin:auto;
*/
.parent{
position: relative;
width: 400px;
height: 400px;
margin:0 auto;
background-color: aqua;
}
.child{
position: absolute;
/* 宽高随意设置 */
width: 150px;
height: 100px;
/* 宽高随意设置,但是有宽高 */
background-color: blueviolet;
top: 0;
left:0;
bottom:0;
right:0;
margin:auto;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">dsaf</div>
</div>
</body>
</html>
方式3:利用transform取代margin负值(子盒子宽高已知未知均可)
算是前两种方式的终极版复合
思路:
*子绝对定位,父相对定位
*同时子元素样式里加:
*left:50%; top:50%; transform:translate(-50%,-50%)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>盒子居中</title>
<style>
/*
*宽高已知或未知的盒子(这里的未知是说存在宽高,但是自己不知道的情况下)
*子绝对定位,父相对定位
*同时子元素样式里加:
*left:50%; top:50%; transform:translate(-50%,-50%)
*/
.parent{
position: relative;
width: 400px;
height: 400px;
margin:0 auto;
background-color: aqua;
}
.child{
position: absolute;
width: 200px;
height: 100px;
background-color: blueviolet;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">dsaf</div>
</div>
</body>
</html>
方式4:利用css3中的transform平移(子盒子宽高已知或未知均可)
子盒子的width已知或未知均可
思路:
*子盒子宽高已知或未知均可
*父元素加:display:flex; justify-content:center; items-align:center;
*即可,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>盒子居中</title>
<style>
/*
*子盒子宽高已知或未知均可
*父元素加:display:flex; justify-content:center; items-align:center;
*即可,
*/
.parent{
position: relative;
width: 400px;
height: 400px;
margin:0 auto;
background-color: aqua;
/* 主要代码 */
display: flex;
justify-content: center;
align-items: center;
/* 主要代码 */
}
.child{
width:150px;
height: 100px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">dsaf</div>
</div>
</body>
</html>