首页 前端知识 html中盒子居中方法

html中盒子居中方法

2024-06-20 09:06:14 前端知识 前端哥 599 895 我要收藏

方法一:flex布局

            /* 弹性容器*/
            display: flex;
             /* 主轴居中 */
            justify-content: center;
             /* 侧轴居中 */
            align-items: center;

缺点:盒子无法覆盖其他标准流

方法二:用magin和padding将盒子挤到中心 

方法三:margin+定位(子绝父相)


            background-color: pink;
            position: absolute;
            left: 50%;
            top:50%;
            margin-left:-100px;
            margin-top:-50px;
            width:200px;
            height:100px;

缺点:盒子的宽高要固定

方法四:定位+margin实现

            position: absolute;
            left: 0;
            top:0;
            bottom: 0;
            right: 0;
            /* 脱离了标准流,margin自适应可以垂直居中、 */
            margin: auto;
            width: 12.5rem;
            height: 6.25rem;
            background-color: pink;

方法五:位移+居中(推荐)

原理:位移取值为百分比数值,参考盒子自身尺寸计算移动距离

            width:200px;
            height:100px;
            background-color: pink;
            position: absolute;
            left: 50%;
            top:50%;
            /* 位移+定位(子绝父相)推荐写法 */
            transform: translate(-50%,-50%);
转载请注明出处或者链接地址:https://www.qianduange.cn//article/12944.html
标签
评论
发布的文章

爱心

2024-06-27 17:06:24

读魏书生的心得体会

2024-07-03 14:07:10

jQuery 选择器

2024-05-12 00:05:34

Vue中public/assets目录区别

2024-07-02 23:07:29

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!