让一个元素垂直居中是我们开发经常遇到的问题,下述整理各种情况:
- <style>
- #content {
- width: 200px;
- height: 200px;
- border: 1px dashed #333;
- }
- #content div{
- width: 50px;
- height: 50px;
- border: 1px solid #f00;
- }
- </style>
- <div id="content">
- <div class="mid"></div>
- </div>
- #content {
- position: relative;
- }
- div.mid {
- position: absolute;
- margin: auto;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
- }
- div.mid {
- position: relative;
- top: 50 % ;
- left: 50 % ;
- margin: -25px 0 0 - 25px;
- /*外边距为自身宽高的一半*/
- }
- div.mid {
- position: relative;
- top: 50 % ;
- left: 50 % ;
- transform: translate( - 50 % , -50 % );
- /*向左上角移动25px,25px*/
- }
属性 | 说明 |
---|---|
transform | 指定应用的变换功能 |
transform-origin | 指定变换的起点(默认元素的中心点) |
transform 属性值
值 | 说明 |
---|---|
translate(<长度值,百分数值>)、translateX、translateY | 在水平方向、垂直方向或者两个方向上平移元素 |
scale(<数值>)、scaleX、scaleY | 在水平方向、垂直方向或者两个方向上缩放元素 |
skew(<角度>)、skewX、skewY | 在水平方向、垂直方向或者两个方向上使元素倾斜一定的角度 |
rotate | 旋转角度 |
matrix(4~6 个数值,逗号隔开) | 指定自定义变换。 |
transform-origin 属性的值
值 | 说明 |
---|---|
<%> | 指定元素 x 轴或者 y 轴的起点 |
<长度值> | 指定距离 |
left、center、right | 指定 x 轴上的位置 |
top、center、bottom | 指定 y 轴上的位置 |
- #content {
- display: flex;
- align - items: center;
- /* 垂直居中 */
- justify - content: center;
- /* 水平居中 */
- }
- <style>
- #content {
- width: 200px;
- height: 200px;
- border: 1px dashed #333;
- }
- </style>
- <div id="content">
- <span>垂直居中,哒啦哒啦,就是它</span>
- </div>
- #content {
- line - height: 200px;
- /*等于其height*/
- }#content span {
- display: inline - block;
- /*设置为行内块*/
- width: 200px;
- overflow: hidden;
- /*防止内容溢出*/
- white - space: nowrap;
- text - overflow: ellipsis;
- }
- #content {
- display: table;
- }
- #content span {
- display: table-cell;
- vertical-align: middle;
- }
上述两者,效果会有所差异
来源: http://www.bubuko.com/infodetail-1958962.html