第一种方式
margin 实现水平方向居中,table-cell + vertical-align 实现垂直方向居中;
<head>
<style>
#parent11 {
width: 300px;
height: 150px;
background-color: greenyellow;
display: table-cell; /* display: table-cell,相当于 td 元素 */
vertical-align: middle; /* vertical-align 控制垂直居中 */
}
#child11 {
width: 100px;
height: 100px;
background-color: green;
margin: auto; /* margin 控制水平居中 */
}
</style>
</head>
<body>
<div id="parent11">
<div id="child11"></div>
</div>
</body>
第二种方式
absolute + transform/margin
实现水平方向和垂直方向居中;
- 解决方案一:left: 0; right: 0; top: 0; bottom: 0; margin: auto;
- 解决方案二:left: 50%; top: 50%; margin: -100px 0 0 -100px;
- 解决方案三:left: 50%; top: 50%; transform: translate(-50%,-50%);
<head>
<meta charset="UTF-8">
<title></title>
<style>
#parent12, #parent13, #parent14 {
width: 300px;
height: 150px;
background-color: greenyellow;
position: relative;
margin-bottom: 5px;
}
#child12 {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
/* 解决方案一:left: 0; right: 0; top: 0; bottom: 0; margin: auto; */
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
#child13 {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
/* 解决方案二:left: 50%; top: 50%; margin: -50px 0 0 -50px; */
left:50%;
top:50%;
margin:-50px 0 0 -50px;
}
#child14 {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
/* 解决方案三:left: 50%; top: 50%; transform: translate(-50%,-50%); */
left:50%;
top:50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div id="parent12">
<div id="child12"></div>
</div>
<div id="parent13">
<div id="child13"></div>
</div>
<div id="parent14">
<div id="child14"></div>
</div>
</body>
第三种方式
flex + justify-content + align-items
实现水平方向和垂直方向居中;
<head>
<meta charset="UTF-8">
<title></title>
<style>
#parent15 {
width: 300px;
height: 150px;
background-color: greenyellow;
display: flex;
justify-content: center; /* 控制水平居中 */
align-items: center; /* 控制垂直居中 */
}
#child15 {
width: 100px;
height: 100px;
background-color: green;
}
</style>
</head>
<body>
<div id="parent15">
<div id="child15"></div>
</div>
</body>
CSS 高级📦 水平居中、垂直居中布局实战套路
上一篇