水平垂直居中
(1)水平居中:
- 元素为行内元素,设置父元素text-align:center
- 如果元素宽度固定,可以设置左右margin为auto
- 如果元素为绝对定位(或相对定位),可以设置父元素position为relative,宽度固定时设置left:0;right:0;margin:auto
- 如果元素为绝对定位(或相对定位),可以设置父元素position为relative,宽度固定时设置left:50%,margin-left值为宽度一半的负值
- 使用绝对定位配合CSS3的transform属性,可以设置父元素position为relative,设置left:50%,transform: translate(-50%,0);(宽度不固定也能实现水平居中)
- 使用
flex
布局,设置父元素display:flex;同时设置justify-content: center; - 使用老版
flex
布局,设置父元素display: -webkit-box;同时设置-webkit-box-pack: center;
(2)垂直居中:
- 文本垂直居中,设置父元素line-height为height值
- 如果元素为绝对定位(或相对定位),可以设置父元素position为relative,高度固定时设置top:0;bottom:0;margin:auto
- 如果元素为绝对定位(或相对定位),可以设置父元素position为relative,高度固定时设置top:50%,margin-top值为高度一半的负值
- 使用绝对定位配合CSS3的transform属性,可以设置父元素position为relative,设置top:50%,transform: translate(0,-50%);(高度不固定也能实现水平居中)
- 使用
flex
布局,设置父元素display:flex;同时设置align-items: center; - 使用老版
flex
布局,设置父元素display: -webkit-box;同时设置-webkit-box-align: center; - 将显示方式设置为表格,设置父元素display: table-cell;同时设置vertical-align: middle;
水平垂直居中想必大家已经司空见惯、见怪不怪了,那假如是父子元素在不知道宽高的情况下实现水平垂直居中呢?
一、子元素是块级元素
方法1、flex布局
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.father {
width: 500px; /*此处未知,方面展示所以假设了宽高*/
height: 300px; /*此处未知,方面展示所以假设了宽高*/
background-color: yellow;
display: flex;
justify-content: center; /*垂直居中*/
align-items: center; /*水平居中*/
}
.child {
width: 200px; /*此处未知,方面展示所以假设了宽高*/
height: 100px; /*此处未知,方面展示所以假设了宽高*/
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
方法2、absolute+CSS3的translate
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.father {
width: 500px;
height: 300px;
background-color: yellow;
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>
二、子元素是行内元素
水平居中:
- 首先看它的父元素是不是块级元素,如果是,则直接给父元素设置 text-align: center;
- 如果不是,则先将其父元素设置为块级元素,再给父元素设置 text-align: center;
垂直居中:
- 只需要设置行内元素的”行高line-height等于盒子的高”即可,仅适用于纯文字;
- 父元素设置成table-cell表格形式,使用vertical-align: middle即可使内联元素垂直居中;
还没有评论,来说两句吧...