zoukankan      html  css  js  c++  java
  • 元素的水平垂直居中的方法

    水平垂直居中

    Html:

      <div id="wrap">
        <div class="box">321</div>
      </div>
    

    其中方法 1、2 必须指定居中元素的高度,方法 3、4 无需指定居中元素的高度

    方法一:

    #wrap{
           500px;
          height: 500px;
          background: gray;
          
          */* 父元素相对定位 */*
          position: relative;
        }
        #wrap .box{
           200px;
          background: deeppink;
    
          */* 必须给定高度 */*
          height: 200px;
          position: absolute;
          top:0;
          left: 0;
          right: 0;
          bottom: 0;
          margin: auto;
        }
    
    

    方法 二:

        #wrap {
           500px;
          height: 500px;
          background: gray;
          */* 父元素相对定位 */*
          position: relative;
        }
    
        #wrap .box {
           200px;
          background: deeppink;
          */* 必须指定高度 */*
          height: 200px;
          position: absolute;
          top: 50%;
          left: 50%;
          */**
    *由于是子元素的左上角距离父元素的左上角 50%,*
    *所以得把上下用 margin 拉回来*
    **/*
          margin-left: -100px;
          margin-top: -100px;
        }
    

    方法三

        #wrap {
           500px;
          height: 500px;
          background: gray;
          */* 父元素相对定位 */*
          position: relative;
        }
    
        #wrap .box {
           200px;
          background: deeppink;
          */* 可以不指定高度 */*
          position: absolute;
          top: 50%;
          left: 50%;
          */**
    *由于是子元素的左上角距离父元素的左上角 50%,*
    *所以得把上下用 translate 拉回来 ,*
    *translate是相对于自己的位置*
    **/*
          transform: translate(-50%, -50%);
        }
    
    

    方法四:

        #wrap {
           500px;
          height: 500px;
          background: gray;
          */* 使用 felx 布局 */*
          display: flex;
          justify-content: center;
          align-items: center;
        }
    
        #wrap .box {
           200px;
          */* 可以不指定高度 */*
          background: deeppink;
        }
    
    
  • 相关阅读:
    CODE[VS] 3026 恶心的扑克
    CODE[VS] 2951 打字比赛
    CODE[VS] 2774 火烧赤壁
    CODE[VS] 1860 最大数 1998年NOIP全国联赛提高组
    matplotlib学习笔记(一)
    LUNA16数据集(二)肺结节可视化
    [转载]pytorch自定义数据集
    [转载]什么情况下应该设置 cudnn.benchmark = True?
    pytorch构建优化器
    pytorch批训练数据构造
  • 原文地址:https://www.cnblogs.com/georgeleoo/p/11430279.html
Copyright © 2011-2022 走看看