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;
        }
    
    
  • 相关阅读:
    程序员面视题解析
    Forms身份验证
    梅花雨日历控件
    系统架构师学习笔记_第四章(下)
    系统架构师学习笔记_第三章
    系统架构师学习笔记_第六章(上)
    系统架构师学习笔记_第五章(下)
    系统架构师学习笔记_第一章
    系统架构师学习笔记_第四章(上)
    系统架构师学习笔记_第五章(上)
  • 原文地址:https://www.cnblogs.com/georgeleoo/p/11430279.html
Copyright © 2011-2022 走看看