CSS样式中的各种居中方式

1、水平居中

将margin-left和margin-right属性设置为auto,从而达到水平居中的效果。

代码:

margin:0 auto;

2、文字水平垂直居中

利用line-height设为height的一样

代码:

line-height: 200px;/*垂直居中关键*/

height: 200px;

3、利用padding和background-clip配合实现div的水平垂直居中

通过backgroun-clip设置为content-box,将背景裁剪到内容区外沿,再利用padding设为外div减去内div的差的一半

 1 .parent{
 2  margin:0 auto;
 3  width:200px;
 4  height:200px;
 5  background-color:red;
 6 }
 7 .children {
 8  width: 100px;
 9  height: 100px;
10  padding: 50px;
11  background-color: black;
12  background-clip:content-box;/*居中的关键*/
4、absolute定位

 其中的margin中的值为该div宽度的一半

 利用position:absolute搭配top,left 50%,再将margin设为负值也可以对div进行水平垂直居中

 1 .parent {
 2  position:relative;
 3  margin:0 auto;
 4  width:200px;
 5  height:200px;
 6  background-color:red;
 7 }
 8 .children {
 9  position:absolute; 
10  left:50%; 
11  top:50%; 
12  margin:-25px 0 0 -25px ;
13  height:50px;
14  width:50px;
15  background-color: black;
16 }

5、text-align居中

将子div的display设为inline-block。

 1 .parent {
 2  text-align:center;
 3  margin:0 auto;
 4  width:200px;
 5  height:200px;
 6  background:red;
 7 }
 8 .children {
 9  positiona;absolute;
10  margin-top:75px;
11  width:50px;
12  height:50px;
13  background: black;
14  display:inline-block;/*使其父元素text-align生效*/
15 }

图片居中

1、top

1 position:absolute;
2  right:50%;
3  bottom:50%;

2、transform

不需要定宽度的父div实现图片的水平垂直居中

1 <div class="parent">
2 
3   <div class="children">
4 
5     <div class="children-inline">我是水平垂直居中噢!</div>
6 
7   </div>
8 
9 </div>
 1 .parent {
 2  float: left;
 3  width: 100%;
 4  height: 200px;
 5  background-color: red;
 6 }
 7 .children {
 8  float:left;
 9  position:relative;
10  top:50%;
11  left:50%;
12 }
13 .children-inline {
14  position: relative;
15  left: -50%;
16  -webkit-transform : translate3d(0, -50%, 0);
17  transform : translate3d(0, -50%, 0);
18  background-color: black;
19  color:white;
20 }

3、flex水平垂直居中

1 <div class="parent">
2 
3   <div class="children">我是通过flex的水平垂直居中噢!</div>
4 
5 </div>
 1 html,body{
 2  width: 100%;
 3  height: 200px;
 4 }
 5 .parent {
 6  display:flex;
 7  align-items: center;/*垂直居中*/
 8  justify-content: center;/*水平居中*/
 9  width:100%;
10  height:100%;
11  background-color:red;
12 }
13 .children {
14  background-color:blue;
15 }
 1 水平居中
 2 .center-vertical {
 3     position: relative;
 4     top: 50%;
 5     transform: translateY(-50%);
 6 }
 7  
 8  
 9  
10 垂直居中
11 .center-horizontal {
12     position: relative;
13     left: 50%;
14     transform: translateX(-50%); 
15 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

靠谱杨

感谢您的认可和鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值