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!
  • 相关阅读:
    arrayAppend.php
    C语言中一个语句太长用什么换行?
    date
    Mysql复制一条或多条记录并插入表|mysql从某表复制一条记录到另一张表
    Unable to load bean org.apache.struts2.dispatcher.multipart.MultiPartRequest
    javascript:location=location;">刷新</a>
    TestAbstract
    scanner=new Scanner(System.in); int i=scanner.nextInt();
    public static void Swap2
    JIRA 模块 bug管理工具
  • 原文地址:https://www.cnblogs.com/Ruth92/p/5490308.html
Copyright © 2011-2022 走看看