zoukankan      html  css  js  c++  java
  • CSS-居中问题

    CSS 中水平垂直居中的几种方法
    1.使用定位流

    原理:盒子先向下偏移父元素高度的50%,再向上偏移盒子高度的50%。

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
    
            html,
            body {
                 100%;
                height: 100%;
            }
    
            div {
                 300px;
                height: 300px;
                background: orange;
                margin: 0 auto;
                position: relative;
                top: 50%;
                margin-top: -150px;
            }
        </style>
    </head>
    
    <body>
        <div></div>
    </body>
    
    </html>
    

    image-20201129214249017

    2.使用transform优化
    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
    
            html,
            body {
                 100%;
                height: 100%;
            }
    
            div {
                 300px;
                height: 300px;
                background: orange;
                margin: 0 auto;
                position: relative;
                top: 50%;
                /* margin-top: -150px; */
                transform: translateY(-50%);
            }
        </style>
    </head>
    
    <body>
        <div></div>
    </body>
    
    </html>
    
    3.使用display: flex;
    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
    
            html,
            body {
                 100%;
                height: 100%;
                display: flex;
                /* 水平居中 */
                align-items: center;
                /* 垂直居中 */      
                justify-content: center;
            }
    
            div {
                 300px;
                height: 300px;
                background: orange;
            }
        </style>
    </head>
    
    <body>
        <div></div>
    </body>
    
    </html>
    
  • 相关阅读:
    CSP2020 T1儒略日 暴力模拟90pts代码
    CSP-S 2019 D1T2括号树
    P3593 [POI2015]TAB
    P5145 漂浮的鸭子
    CH0503 奇数码问题
    [NOIP2012]国王游戏 -高精度-贪心-
    费解的开关
    P1040 加分二叉树
    初步学习线段树
    P2758 编辑距离 简单DP
  • 原文地址:https://www.cnblogs.com/toyz9/p/14058262.html
Copyright © 2011-2022 走看看