zoukankan      html  css  js  c++  java
  • div 固定宽高 水平垂直居中方法

        div固定宽高,水平垂直居中,根据所用单位不同,分成两种情况,分别是“px”和“%”情况。

        例:将三层div做出三个边框,要求水平垂直居中。效果如图

           

    • 情况一(单位是px时):

           只需要用绝对定位到屏幕中间,然后利用margin-left和margin-top取值就可以实现。

     1 <style type="text/css">
     2 
     3 .a {
     4     border: 1px solid #00caca;
     5      width: 900px;
     6     height: 500px; 
     7     position: absolute;
     8     top: 50%;
     9     left: 50%;
    10     margin-left: -450px;
    11      margin-top: -250px;
    12 
    13     display: flex;   //flex让内部div水平垂直居中
    14     flex-direction: row;
    15     justify-content: center;
    16     align-items: center; 
    17 }
    18  .b {
    19     border: 1px solid #00cacc;
    20     width: 80%;
    21     height: 70%;
    22     display: flex;
    23     flex-direction: row;
    24     justify-content: center;
    25     align-items: center;
    26 }
    27 .c {
    28     border: 1px solid #00fffb;
    29     width: 60%;
    30     height: 60%;
    31 }
    <body>
        <div class="a">
            <div class="b">
                <div class="c">ssssss</div>
            </div>
        </div>
    </body>
    • 情况二(单位是%):

          由于%是基于父元素宽高,采用margin-left值为负本身宽高一半失效,因此,需要计算定位top 和 left值,使其居中。代码如下,其中,HTML结构不变。

    <style type="text/css">
    body {
        width: 100%;     //需要给body设置宽高
        height: 100%;
    } 
    .a {
        border: 1px solid #00caca;
         width: 80%;
        height: 80%; 
        position: absolute;
        top: 10%;    //根据自身宽高占body的80%,推算定位top值
        left: 10%;    //同上
         margin-left: 0;
         margin-top: 0; 
    
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center; 
    }
     .b {
        border: 1px solid #00cacc;
        width: 80%;
        height: 70%;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
    }
    .c {
        border: 1px solid #00fffb;
        width: 60%;
        height: 60%;
    } 
    </style>
  • 相关阅读:
    [补]2019HDU杭电多校第一场A
    [补]2019nowcoder牛客第三场F(暂且)
    [补]2019nowcoder牛客第一场E、I
    [学]从零(多项式基础与FFT)开始BM学习笔记
    [补]2019nowcoder牛客第二场E、H(upd0730)
    从一个简单的例子对win 服务程序进行讲解
    HTTP协议学习记录及总结
    Windows身份验证与forms身份验证的结合
    关于Sql server 的 几道面试题
    PlaceHolder控件的使用
  • 原文地址:https://www.cnblogs.com/lovemomo/p/6077625.html
Copyright © 2011-2022 走看看