常见css样式居中方法
1. 垂直居中
1.1 单行元素垂直居中
- css中没有文字垂直居中的代码
- 解决方法:让文字的行高等于盒子高度。
1.2 多行元素垂直居中
利用flex布局:flex-direction: column定义主轴方向为纵向。因为flex布局是CSS3中定义,在较老的浏览器存在兼容性问题。
核心代码:
.center-flex {display: flex;flex-direction: column;justify-content: center;
}
1.3 块级元素垂直居中
已知居中元素的高度和宽度,通过绝对定位元素距离顶部50%,并设置margin-top向上偏移元素高度的一半,就可以实现垂直居中了。
核心代码:
.parent {position: relative;
}
.child {position: absolute;top: 50%;height: 100px;margin-top: -50px;
}
2. 水平垂直居中
2.1 固定宽高元素水平垂直居中
通过margin平移元素整体宽度的一半,使元素水平垂直居中。
核心代码:
.parent {position: relative;
}
.child {width: 300px;height: 100px;padding: 20px;position: absolute;top: 50%;left: 50%;margin: -70px 0 0 -170px;
}
2.2 未知宽高元素水平垂直居中
利用2D变换,在水平和垂直两个方向都向反向平移宽高的一半,从而使元素水平垂直居中。
核心代码:
.parent {position: relative;
}
.child {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);
}
2.3 利用flex布局
利用flex布局,其中justify-content 用于设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式;而align-items属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。
核心代码:
.parent {display: flex;justify-content: center;align-items: center;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
