1. 程式人生 > >不固定寬高元素水平垂直居中

不固定寬高元素水平垂直居中

背景: 本文主要講述不用flex佈局和grid佈局時如何設定不定高寬元素的水平垂直居中,這是很多時候經常遇到的問題。

頁面結構

  <div class="box">
  	<div class="content"><span>hell</span><br/>ssssssss<br/>shshsh
  		</div>
  </div>

第一種方法(absolute+translate)不相容ie8,因為這個transform屬性不相容ie8

translate裡面的百分比是以自身大小為基準的

		.box
{ width:400px; height: 400px; background-color: skyblue; position: relative; } .content{ position: absolute; top:50%; left:50%; transform: translate(-50%,-50%); }

在這裡插入圖片描述 第二種方法(table-cell+inline-block)不相容ie67,因為inline-block識別不了

將div設定成表格的單元格,使用vertical-align、text-align屬性將內聯元素對齊

		.box{		
			width:400px;
			height: 400px;
			background-color: skyblue;
			display: table-cell;
			vertical-align: middle;
			text-align: center;
		}
		.content{
            display: inline-block;
		}

在這裡插入圖片描述 假的方法(top.left.right.bottom為0+margin:auto)

這種方法不知道怎麼以訛傳訛說能夠實現不定寬高的垂直居中的,實際上是不行的,當content沒有寬高時會繼承父元素的寬高

//不設定寬高
		.box{		
			width:400px;
			height: 400px;
			background-color: skyblue;
            position: relative;
		}
		.content{
            position: absolute;
            top:0;
            left:0;
            right:0;
            bottom: 0;
            margin: auto;
		}

在這裡插入圖片描述

//設定寬高
		.box{		
			width:400px;
			height: 400px;
			background-color: skyblue;
            position: relative;
		}
		.content{
            position: absolute;
            top:0;
            left:0;
            right:0;
            bottom: 0;
            width:50%;
            height:50%;
            margin: auto;
		}

在這裡插入圖片描述