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

  • 相关阅读:
    树-构建二叉树
    爬虫-scrapy框架详解(17)
    How to identify the HBA cards/ports and WWN in Linux
    NetBackup常用网络端口整理
    keepalived+MySQL实现高可用
    nginx配置https双向验证(ca机构证书+自签证书)
    systemd设置nginx开机自启动
    Keepalived+Nginx搭建主从高可用并带nginx检测
    windows 挂在EMC 存储
    linux时间同步,ntpd、ntpdate
  • 原文地址:https://www.cnblogs.com/qxz17760485467/p/11568533.html
Copyright © 2011-2022 走看看