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

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8" />
            <title></title>
            <style type="text/css">
            </style>
        </head>
        <body>
            <div class="father">
                <div class="son">1111</div>
            </div>
        </body>
    </html>


    1.(使用绝对布局): 这种方式的弊端是:必须要知道这个容器的长宽,因为在子元素中的    margin-top:-100px;    margin-left:-100px; 这两个样式分别是子元素长、宽的一半。
     

    .father {
      width: 500px;
      height: 500px;
      position: relative;
      background-color: red;
    }
     
    .son {
      width: 200px;
      height: 200px;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-left: -100px;
      background-color: black;
    }


    2.万能方式:仍然是绝对布局,让left和top都是50%,这在水平方向上让div的最左与屏幕的最左相距50%,垂直方向上一样,所以再用transform向左(上)平移它自己宽度(高度)的50%,也就达到居中效果了,效果图和上方相同。//这种方式很好的避免了方式一的弊端,不需要知道自己的长宽,一样可以定位到中间
      

    .father{
      width: 1000px;
      height: 600px;
      position: relative;
      background-color: red;
    }
    .son {
      background-color: #fff;
      width: 300px;
      height: 300px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }


    3.万能方法(使用弹性布局flex) //这种方式比较通用:这样给父元素设置了三个样式display:flex;(弹性布局)    justify-content:center;(内容水平居中)   align-items:center; (内容垂直居中) 就可以达到水平、垂直居中的效果
     

    .father {
      width: 500px;
      height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: red;
    }
    .son {
      width: 200px;
      height: 200px;
      background-color: black;
    } 


    4.方法四(使用绝对布局) //使用这种方式的要领是:子绝父相,且子元素要设置以下的样式position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; 就可以达到居中效果

    .father {
      width: 500px;
      height: 500px;
      position: relative;
      background-color: red;
    }
     
    .son {
      width: 200px;
      height: 200px;
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;
      background-color: black;
    }
  • 相关阅读:
    iOS 解析xml
    带滚动条html,js获取鼠标位置
    iOS ViewController利用代理页面传值
    Android Volley完全解析
    32位linux中无法使用AVD的解决方案
    8年前在公交上被年轻小伙打了,76岁大爷苦练功夫“复仇”成功...网友:大爷,你一定是天蝎座的吧
    退学,离家出走,卖房创业,在他即将烧完最后一笔钱时,获250万元融资
    夏普将在迪拜推出植物工厂种草莓
    国产手机出货量今年要追平苹果三星,到底有多难?
    原生ajax动态添加数据
  • 原文地址:https://www.cnblogs.com/roboot/p/15401403.html
Copyright © 2011-2022 走看看