zoukankan      html  css  js  c++  java
  • CSS 实现:元素相对于文档水平垂直居中

    【要求】:如何用 CSS 实现水平/垂直居中一个元素(相对于文档)

    <body>
        <div class="content"></div>
    </body>
    

    【实现】:

    ① margin + 相对定位(relative)

    // html 和 body 的高度默认为0,因此要先设置为100%,并且清除默认样式(margin:0; padding:0)
    
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    
    .content {
         200px;
        height: 200px;
        background: #0f0;
        
        margin: 0 auto;	// 水平居中
        position: relative;	// 相对于自身静态位置进行定位
        top: 50%;	// 向下偏移 body 高度的50%
        transform: translateY(-50%); // 向上偏移自身高度的 50%
    }
    

    ② 不使用 margin,只用相对定位(relative)

    // html 和 body 的高度默认为0,因此要先设置为100%,并且清除默认样式(margin:0; padding:0)
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    
    .content {
         200px;
        height: 200px;
        background: #0f0;
        
        position: relative;	// 相对于自身静态位置进行定位
        top: 50%;	// 向下偏移 body 高度的50%
        left: 50%;	// 向左偏移 body 宽度的50%
        transform: translate(-50%, -50%); // 向上/左偏移自身高度/宽度的 50%
    }
    

    注意,实现二中的 transform 不能分开写,类似于下面这样,这样后写的 transform 会覆盖先写的,将导致只能实现一处偏移。

    top: 50%;
    left: 50%;
    transform: translateX(-50%);
    transform: translateY(-50%);
    

    ③ 使用 absolute + margin: auto;

    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
        position: relative;
    }
    
    .content {
         200px;
        height: 200px;
        background: #0f0;
    
        position: absolute;
        margin: auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
    }
    

    效果预览


    Scoop It and Enjoy the Ride!
  • 相关阅读:
    CSS3 object-fit 图像裁剪
    jQuery.extend 使用函数
    ios 不支持iframe 解决方案
    详解HTML5中rel属性的prefetch预加载功能使用
    web页面加载、解析、渲染过程
    TCP的三次握手(建立连接)与 四次挥手(关闭连接)
    html---规范、细节积累-01
    pio设置单元格式
    让一个数字显示指定位数
    linux下获取微秒级精度的时间
  • 原文地址:https://www.cnblogs.com/Ruth92/p/5490308.html
Copyright © 2011-2022 走看看