设为首页 加入收藏

TOP

css样式水平居中和垂直居中的方法
2019-09-23 11:14:19 】 浏览:31
Tags:css 样式 水平 中和 垂直 居中 方法

水平居中(包含块中居中)

1. 定宽,左右margin为auto。(常规流块盒、弹性项目[不用定宽])

例子:在box1盒子上设置宽,再设置margin:auto;

<style>
    .box1 {
        width: 200px;
        height: 200px;
        background-color: black;
        margin: auto;
    }
</style>

<body>
    <div class="box-all">
        <div class="box1"></div>
    </div>
</body>

得到的效果:

 

 

 

2. 弹性盒设置justify-content: center,让弹性项目在主轴上居中。(普遍适应)

例子:在其父元素上设置弹性盒子,和对齐方式;

<style>
    .box-all {
        display: flex;
        justify-content: center;
    }
    
    .box1 {
        width: 200px;
        height: 200px;
        background-color: black;
    }
</style>

<body>
    <div class="box-all">
        <div class="box1"></div>
    </div>
</body>

得到的效果:

3. 父元素设置text-align: center,让其内部的行盒、块盒居中(文本)。

例子:在盒子上设置text-align:center;文本自动居中;

<style>
    p {
        text-align: center;
    }
</style>

<body>
    <div class="box-all">
        <p>这是一段文本。</p>
    </div>
</body>

得到的效果:

 

 

 

4. 相对定位元素,margin-left:50%? transform:translateX( -50%)。[margin,padding相对于包含块宽度的百分比] 【终极方案】

例子:对盒子设置相对定位属性,在用上面方式进行定位;

<style>
    .box1 {
        width: 200px;
        height: 200px;
        background-color: black;
        position: relative;
        margin-left: 50%;
        transform: translateX(-50%);
    }
</style>

<body>
    <div class="box-all">
        <div class="box1"></div>
    </div>
</body>

得到的效果:


垂直居中(方法与上面类似,我就不演示了)

1. 单行文本垂直居中,设置父元素的line-height为包含块高度。

2. 弹性盒设置align-items:center,让弹性项目在侧轴上居中。

3. 相对定位元素,top:50%;transform:translateY(-50%)。【终极方案】

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇小程序九九八十一坑之跳转传参 下一篇vue学习总结

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目