栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Html/CSS > CSS教程

关于水平居中垂直居中的常用方法

CSS教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于水平居中垂直居中的常用方法

最近看了很多大神的各种关于水平居中和垂直居中的方法。我觉得用自己的话来写一遍可能记忆比较深一点。我记下几个我觉得比较常用的方法。
水平居中
行内元素,给其父元素设置text-align:center,就可以实现行内元素水平居中

 

    .box {text-align: center;}

    
 我要居中啦
我也居中啦
 

    .box1 {width: 200px;height: 100px;background: #f0f0f0;margin: 0 auto;text-align: center;line-height: 100px;}
    p{width: 200px;height: 100px;background: #989898;margin: 0 auto;text-align: center;line-height: 100px;}

    我是div   
    

我是p标签

垂直居中


    div{width: 300px;height: 50px;}
    p{line-height: 50px;}

    
 

我是垂直居中

 

    .box{width: 500px;height:300px;display: table-cell;background: #f0f0f0;vertical-align: middle;}


    
 我是垂直居中
 我是测试文字啦啦啦我是测试文字啦啦啦
 我是垂直居中
 我是测试文字啦啦啦我是测试文字啦啦啦
 我是垂直居中
 我是测试文字啦啦啦我是测试文字啦啦啦我是测试文字啦啦啦
 我是垂直居中
 我是测试文字啦啦啦我是测试文字啦啦啦
    

水平垂直居中

 

    .box{width: 200px;height:300px;background: #f0f0f0;position: absolute;top:50%;margin-top: -150px;left: 50%;margin-left: -100px;}


    
 cdfdsfsf 
    


    .box{display: flex;height: 300px;background: #ccc;}
    .box-child{width: 100px;height: 100px;margin: auto;background: #ddd;}

    
 sdfs
    


    .box{position: absolute;top:50%;left:50%;transform: translate(-50%,-50%);-webkit-transform: translate(-50%,-50%);-moz-transform: translate(-50%,-50%);-o-transform: translate(-50%,-50%);background: #ccc;}

    
 因为不知道宽高度,所以主要用translate属性拉回未知元素XY轴上的位置实现居中
若是单纯实现未知高度的元素居中,只要用到transform:translateY(-50%)即可实现


    .box{display: flex;justify-content: center;align-items: center;height: 300px;background: #ccc;}
    .box-child{width:200px;height: 100px;border:1px solid #ddd;}

    
 
     定义居中元素的父元素justify-content和align-items属性为center即可, 
需要设置足够的高度,不然只有水平居中效果
 
    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/242699.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号