美文网首页
css实现自适应正方形

css实现自适应正方形

作者: meng_281e | 来源:发表于2018-10-11 11:02 被阅读0次

    1、vm单位

    <div class="square-shape"></div>
    .square-shape {
      width: 50%;
      height: 50vw;
      border: 1px solid #f00;
    }
    

    2、padding-top实现

    <div class="square-shape"></div>
    .square-shape {
      width: 50%;
      height: 0; 
      padding-top: 50%;
      border: 1px solid #f00;
    }
    

    3、padding-bottom实现

    <div class="square-shape"></div>
    .square-shape {
      width: 50%;
      height: 0;
      padding-bottom: 50%;
      border: 1px solid #f00;
    }
    

    4、伪元素的margin-top

    <div class="square-shape"></div>
    .square-shape {
      width: 100%;
      overflow: hidden;
      border: 1px solid #f00;
    }
    .square-shape:after {
      content: '';
      display: block;
      margin-top: 100%;
    }
    

    5、伪元素的padding-top

    <div class="square-shape"></div>
    .square-shape {
      width: 30%;
      max-width: 200px;  
      border: 1px solid #f00;
    }
    .square-shape:after {
      content: '';
      display: block;
      padding-top: 100%;
    }
    

    6、子元素margin-top

    <div class="square-shape">
      <div class="content"></div>
    </div>
    .square-shape{
      overflow: hidden;
      width: 50%;
      background-color: black;
    }
    .content{
      margin-top: 100%;
    }
    

    7、伪元素的padding-bottom,内嵌absolute元素

    <div class="square-shape">
        <div class="content"></div>
    </div>
    .square-shape {
      width: 50%;
      border: 1px solid #f00;
    }
    .square-shape:after {
      content: '';
      display: block;
      padding-bottom: 100%;
    }
    .content {
      position: absolute;
      width: 100%;
      height: 100%;
    }
    

    相关文章

      网友评论

          本文标题:css实现自适应正方形

          本文链接:https://www.haomeiwen.com/subject/gknvaftx.html