CSS——垂直水平居中
文章目录
- 一、垂直居中
- transform方法,calc方法
- flex方法
- line-height方法
- 伪元素(::after,::before)方法
- 绝对定位(margin:auto)方法
- 二、水平居中
- 行内元素
- 块级元素
- 其他方法
- 总结
一、垂直居中
transform方法,calc方法
元素高度已知的情况下,可以使用calc函数动态计算达到垂直居中所需高度
calc(50%-?px),?为自身高度一半
calc为css3新增,可以使用top: 50%; margin-top: -?px; 代替
.center {height: 300px;background: #f00;
}
.center div {position: relative;width: 100px;height: 100px;background: #0ff;top: calc(50% - 150px);
}
元素高度未知的情况,可以使用 transform中的translate参数对元素自身进行平移
translate参数是以元素本身的宽高为基准,所以向上平移自身高度50%的距离即可实现垂直居中
子元素必须要加上position:relative,否则无效
.center {height: 1000px;background: #f00;
}
.center div {position: relative;top: 50%;transform: translateY(-50%);
}
flex方法
使用flex布局,将align-items参数设定为居中即可
.center {display: flex;align-items: center;height: 300px;background: #f00;
}
.center div {width: 100px;height: 100px;background: #0ff;
}
line-height方法
该方法仅适用于“单行”的“行内元素”
.center {height: 100px;background: #f00;line-height: 100px;text-align: center;
}
.center div {display: inline-block;background: #0ff;
}
伪元素(::after,::before)方法
面对多行的元素时可以使用此方法解决垂直居中问题
.center {height: 300px;background: #f00;text-align: center;
}
.center::after {content: "";display: inline-block;vertical-align: middle;height: 100%;
}
.center div {height: 100px;width: 100px;display: inline-block;vertical-align: middle;background: #0ff;
}
绝对定位(margin:auto)方法
使用绝对定位方法,将元素的position指定为absolute,父元素的position必须要指定为relative
将top,left,right,bottom都设置为0,让子盒子与父容器的间距为0
top,left,right,bottom属性只在position存在且不为"static"时生效
.center {position: relative;height: 300px;background: #f00;
}
.center div {height: 100px;width: 100px;position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;background: #0ff;
}
二、水平居中
行内元素
.center{text-align:center;
}
块级元素
元素宽度已知,直接使用margin
.center {width: 100px;margin: 0 auto;background-color: #f00;
}
元素宽度未知,将元素设为display:table
.center {display: table;margin: 0 auto;background-color: #f00;
}
其他方法
水平居中与垂直居中多数方法的使用是类似的,在flex布局中使用justify-content:center;即可实现水平居中
使用position + calc,position +transform,以及绝对定位设四方间距为0,margin:auto的方法均可实现
总结
在平常学习中对于垂直居中问题,使用flex和transform的次数较多,今天总结了更多解决方法,在不同环境下使用对应的方法以便更妥善的解决问题,对于各类方法的基础使用有所掌握,对于部分方法的实现原理和弊端还不太了解,等工作之后深入学习再加以扩展。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
