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;
        }
    
    
  • 相关阅读:
    多版本node安装197
    linux 测试麦克风197
    解决linux写入ntfs盘时报错:只读文件系统197
    freemarker 解析纯json字符串197
    manjaro mysql安装197
    manjaro安装微信197
    manjaro 安装输入法197
    strings包 — 汇总
    proc 目录介绍
    learning、trying、teaching
  • 原文地址:https://www.cnblogs.com/georgeleoo/p/11430279.html
Copyright © 2011-2022 走看看