zoukankan      html  css  js  c++  java
  • 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%)。【终极方案】

  • 相关阅读:
    HDU 3415 Max Sum of Max-K-sub-sequence 最长K子段和
    Android Fragment 真正彻底的解决(下一个)
    【数据分析面试题】一个 面试题,我的回答
    Swift初体验(两)
    MyEclipse10.0 集成 SVN
    CFileDialog 打开文件夹文件 保存文件夹文件
    基于thinkphp的uploadify上传图功能
    近20家银行手机银行签名被非法滥用风险分析
    设计模式【6】:适配器模式【接口适配】
    【学习笔记】编译原理-有限自己主动机
  • 原文地址:https://www.cnblogs.com/Taiweis/p/11568533.html
Copyright © 2011-2022 走看看