css——居中对齐方法

1、text-align:center —— 水平居中

仅对文字、图片、按钮等行内元素有效(display设置为inline或inline-block等)进行水平居中

2、margin:垂直 auto; —— 水平居中

仅水平居中,且对浮动元素定位无效

 .father{
           width:500px;
           height:200px;
           background-color::#f98769;
           overflow:hidden;//不可缺少否则margin-top不生效
       }
        .son{
            width: 100px;
            height: 100px;
            margin:50px auto ;
            background-color: #ff0000;
        }
3、line-height —— 垂直居中

line-height=height ,仅对一行文字有效

4、使用表格 —— 水平、垂直居中

对td/th的align=‘center’和valign=‘middle’两属性可以水平和垂直居中

5、弹性布局 —— 水平、垂直居中
.father{
display:flex;
justity-content:center;
align-items:center;
}
.father{
display:flex;
flex-direction:column;//改变主轴为cross axis
justity-content:center;
}
6、使用display:table-cell —— 水平、垂直居中

对于那些不是表格的元素,我们可以通过display:table-cell 来把它模拟成一个表格单元格

.father{
    height:300px;
    background:#ccc;
    display:table-cell; /*IE8以上及Chrome、Firefox*/
    vertical-align:middle; /*IE8以上及Chrome、Firefox*/
    text-align:center;
 }
 .son{
 display:inline-block;//或是inline
 }
7、奇淫技巧——子绝父相(已知子元素宽高) —— 水平、垂直居中
.father{
position:relative;
}
.son{//m、n为子盒子宽、高的一半
position:absolute;
left:50%;
top:50%;
margin-left:-mpx;
margin-top:-npx;
8、未知子元素宽高 —— 水平、垂直居中
.father {
    position:relative;
}
.son {
    position:absolute;
    top:50%;
    left:50%:
    transform:translate(-50%,-50%) /*单独设置transform:translateY(-50%);*/
}
9、伪元素法 —— 垂直居中
		 .father{
            position: relative;
        }
        .father::before{
            content: " ";
            display: inline-block;
            height: 100%;
            width: 1%;
            vertical-align: middle;
        }
        .son{
            display: inline-block;
            vertical-align: middle;
        }  
  • 11
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值