CSS/CSS3实现水平垂直居中

**

CSS/CSS3实现水平垂直居中

**

前端页面中元素的水平垂直是比较常见的,下面来写几种css/css3实现的未知宽高元素的水平和垂直居中的写法。

第一种 css3的transform

.father{
/*设置元素相对定位*/
     position: relative;
}
.son{
/*设置元素绝对定位*/
    position:absolute;
/*top 50%*/
    top: 50%;
/*left 50%*/
    left: 50%;
/*css3   transform 实现*/
    transform: translate(-50%, -50%);
}

第二种 flex弹性盒子布局

.father{
/*弹性盒模型*/    
    display:flex;
/*主轴居中对齐*/
    justify-content: center;
/*侧轴居中对齐*/    
    align-items: center;  
}

第三种 flex+margin:auto

.father{
/*弹性盒模型*/  
        display: flex;
}
 .son{
        margin: auto;
 }

第四种 display的table-cell

在父元素设置text-align和vertical-align,并将父元素设置为table-cell元素,子元素设置为inline-block元素

.father{
/*让元素渲染为表格单元格*/
    display:table-cell;
/*设置文本水平居中*/
    text-align:center; 
/*设置文本垂直居中*/
    vertical-align:middle;     
}
.son{
   display: inline-block;
}
    

第五种 绝对定位配合margin

利用绝对定位元素的盒模型特性,在偏移属性为确定值的基础上,设置margin:auto

.father{
/*设置元素相对定位*/
    position: relative;
}
.son{
/*设置元素绝对定位*/
    position:absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    margin:auto;
}   
    

第六种 grid网格布局

[注意]IE10-浏览器不支持

.father{
     display: grid;
}
.son{
    align-self: center;
    justify-self: center;
}  
   /*第二种*/ 
  .father{
        display: grid;
        align-content: center;
        justify-content: center;
}
    

第七种 水平对齐+行高

实现单行文本水平垂直居中

.father{
        text-align: center;
        line-height: 100px;
 }
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值