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布局无疑方便很多,但同样存在兼容性问题;

  • 相关阅读:
    招财宝和余额宝哪个好?注意招财宝三大漏洞
    JavaScript eval() Function
    面向对象设计七大原则
    Web开发应该注意的问题
    表格内容排序(js实现)
    Ruby on Rails Tutorial 第六章 用户模型
    Ruby on Rails Tutorial 第五章 完善布局
    一万小时定律的数学解释
    数据抓取的艺术(三)
    数据抓取的艺术(二)
  • 原文地址:https://www.cnblogs.com/haveadate/p/13994375.html
Copyright © 2011-2022 走看看