zoukankan      html  css  js  c++  java
  • 子元素在父元素中水平垂直居中的几种方式

    子元素、父元素HTML结构如下:

    <div class="wrapper">
    	<div class="inner"></div>
    </div>
    

    1. 定位 + top/left/bottom/right 值相等

    .wrapper {
    	position: relative;
    	 300px;
    	height: 300px;
    	border: 1px solid #333;
    	margin: 50px auto;
    }
    
    .inner {
    	position: absolute;
    	top: 0;
    	left: 0;
    	bottom: 0;
    	right: 0;
    	 100px;
    	height: 100px;
    	border: 1px solid #333;
    	margin: auto;
    }
    

    注意:一定要加上margin:auto

    特点:此方式不存在兼容性问题;

    2. 定位 + margin

    .wrapper {
    	position: relative;
    	 300px;
    	height: 300px;
    	border: 1px solid #333;
    	margin: 50px auto;
    }
    
    .inner {
    	position: absolute;
    	top: 50%;
    	left: 50%;
    	 100px;
    	height: 100px;
    	border: 1px solid #333;
    	margin-top: -50px;
    	margin-left: -50px;
    }
    

    特点:不存在兼容性问题,但是需要事先知道子元素的宽高;

    3. 定位 + 平移(translate)

    .wrapper {
    	position: relative;
    	 300px;
    	height: 300px;
    	border: 1px solid #333;
    	margin: 50px auto;
    }
    
    .inner {
    	position: absolute;
    	top: 50%;
    	left: 50%;
    	 100px;
    	height: 100px;
    	border: 1px solid #333;
    	transform: translate(-50%, -50%);
    }
    

    特点:不需要事先知道子元素的宽高,相对来说比方法2更加方便,但是使用了CSS3的属性(transform),存在兼容性问题;

    4. flex布局

    .wrapper {
    	display: flex;
    	justify-content: center;
    	align-items: center;
    	 300px;
    	height: 300px;
    	border: 1px solid #333;
    	margin: 50px auto;
    }
    
    .inner {	
    	 100px;
    	height: 100px;
    	border: 1px solid #333;
    }
    

    特点:相对于前面几种方式,flex布局无疑方便很多,但同样存在兼容性问题;

  • 相关阅读:
    编程随想——从基础开始,顺其自然
    多个SSH私钥配置不当导致Git push 失败的分析及解决方法
    VPS配置记录
    COCI 2010.03.06 T5「PROGRAM」题解
    筛素数
    你的第一个程序--基本输入输出介绍,头文件介绍
    入门指北目录
    尺取法
    HAOI2006 (洛谷P2341)受欢迎的牛 题解
    c++并查集配合STL MAP的实现(洛谷P2814题解)
  • 原文地址:https://www.cnblogs.com/haveadate/p/13994375.html
Copyright © 2011-2022 走看看