zoukankan      html  css  js  c++  java
  • css居中

    文本居中:style="text-align:center;line-height == heigh"

    水平居中: 设置元素宽度后,设置margin: 0 auto;(把左和右外边距设置为 auto,规定的是均等地分配可用的外边距。结果就是居中的元素)

                       margin:auto;也只是水平居中,因为“如果”margin-top“或”margin-bottom“为”auto“,则其使用值为0”,结果等于margin: 0 auto;

    水平垂直居中

    方法1:首先,创建两个方形,一个包含在另一个里面,我们希望里面的那一个相对于外面的那个来定位,则需要用到position属性<!DOCTYPE html><html lang="en">

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            div {
                 200px;
                height: 200px;
                background-color: springgreen;
                position: relative;
            }
    
            .box {
                 100px;
                height: 100px;
                background-color: slateblue;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
            }
        </style>
    </head>
    
    <body>
        <div>
            <div class="box"></div>
        </div>
    </body>
    
    </html>

    内层元素的position: absolute; 外层元素的position: relative; 内层元素会一直往外层元素找,找到position为relative的元素后,相对这个元素定位,如果没找到,按最外层body定位

    当不设置transform时的效果图如左图,我们希望居中,则将内层方块往上和左移动它的50%的距离即可,则设置transform后的样式如右图                

                                                                                                   

     方法2 :将元素的 left bottom top right 全部设为0,再设置margin:auto;

    div {
                 200px;
                height: 200px;
                background-color: springgreen;
                position: relative;
            }
    
            .box {
                 100px;
                height: 100px;
                background-color: slateblue;
                position: absolute;
                /* position: fixed; */
                left: 0;
                top: 0;
                right: 0;
                bottom: 0;
                margin: auto;
            }

    如果想相对整个页面居中,则将position设置为fixed即可。

  • 相关阅读:
    横竖屏切换
    org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: unknown encoding
    @Value() 使用方法
    调用第三方超时处理
    spring 配置注解定时器quartz01
    tomcat:PermGen space
    06-图3 六度空间 (30分)
    06-图2 Saving James Bond
    06-图1 列出连通集 (25分)
    05-树9 Huffman Codes (30分)
  • 原文地址:https://www.cnblogs.com/sycamore0802/p/12883962.html
Copyright © 2011-2022 走看看