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%)。【终极方案】

  • 相关阅读:
    8.10
    今日头条笔试题 1~n的每个数,按字典序排完序后,第m个数是什么?
    Gym 100500B Conference Room(最小表示法,哈希)
    CodeForces 438D The Child and Sequence(线段树)
    UVALIVE 6905 Two Yachts(最小费用最大流)
    Gym Conference Room (最小表示法,哈希)
    hdu 2389 Rain on your Parade(二分图HK算法)
    Codeforces Fox And Dinner(最大流)
    zoj 3367 Counterfeit Money(dp)
    ZOJ3370. Radio Waves(2-sat)
  • 原文地址:https://www.cnblogs.com/Taiweis/p/11568533.html
Copyright © 2011-2022 走看看