純CSS設置元素垂直水平居中的幾種方法

分爲定位的方法,和不定位的方法。

使用定位的方法:
  1. 定位+transform:
    父元素相對定位,子元素絕對定位,設置子元素的 top:50%; left:50%;transform:translate: (-50%,-50%),代碼對應類名f1,box1。
  2. 定位+margin:
    父元素相對定位,子元素絕對定位,設置子元素的 top:50%; left:50%;margin-left:負的自身寬度的一半,margin-top:負的自身高度的一半。代碼對應類名f1,box1。代碼都寫在了這一部分裏,有標註。
  3. 定位+margin:
    父元素相對定位,子元素絕對定位。設置子元素的left,right,bottom,top都爲0,margin:auto;代碼對應類名f3,box3。
不用定位的方法:
  1. table-cell方法,賦予父元素單元格的屬性:
    父元素display:table-cell; vertical-align: middle;設置子元素的margin:0 auto;代碼對應類名 f2,box2。
  2. flex彈性盒子佈局:
    設置父元素display: flex;
    justify-content: center;
    align-items: center;
    代碼對應類名 f4,box4。
html代碼:

外層div與內層div,span標籤區分第幾種,序號。

<body>
	<span>1</span>
	<div class="f1">
		<div class="box1"></div>
	</div>
	<span>2</span>
	<div class="f2">
		<div class="box2"></div>
	</div>
	<span>3</span>
	<div class="f3">
		<div class="box3"></div>
	</div>
	<span>4</span>
	<div class="f4">
		<div class="box4"></div>
	</div>
</body>
style內容:
.f1 {
			width: 300px;
			height: 200px;
			border: 1px solid red;
			position: relative;
		}

		.box1 {
			position: absolute;
			width: 100px;
			height: 50px;
			background-color: pink;
			/*父元素相對定位,
			子元素絕對定位,
			設置子元素的 top:50%; left:50%;
			transform:translate: (-50%,-50%)
			*/
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			/* 方法2:父元素相對定位,子元素絕對定位
			設置子元素:
			top:50%; 
			left:50%;
			margin-left: 負的寬度一半 
			margin-top: 負的高度一半。
			這兩種類似,我寫在了一個類裏面。
			 */			
			/* margin-left: -50px;
			margin-top: -25px; */
		}


		.f2 {
			width: 300px;
			height: 200px;
			background: rgb(241, 241, 43);
			border: 1px solid #555555;
			/* 方法3:父元素display:table-cell;vertical-align:middle;
			子元素:margin:0 auto;*/
			display: table-cell; /*轉換爲table單元格顯示*/
			/*垂直居中*/
			vertical-align: middle;			
		}

		.box2 {
			width: 100px;
			height: 100px;
			background: pink;
			margin: 0 auto;
			/*水平居中*/
		}

		.f3 {
			width: 300px;
			height: 200px;
			border: 1px solid red;
			background: lightyellow;
			/* 方法4:
			父元素相對定位,子元素絕對定位,
			設置子元素left,right,bottom,top都爲0,margin:auto;*/
			position: relative;
		}

		.box3 {
			position: absolute;
			width: 100px;
			height: 100px;
			background: pink;

			left: 0;
			top: 0;
			bottom: 0;
			right: 0;
			margin: auto;
		}

		.f4 {
			width: 300px;
			height: 200px;
			border: 1px solid red;
			background: lightyellow;
			/*方法5:flex彈性盒子佈局
			設置父元素display: flex;
			justify-content: center;
			align-items: center;*/
			display: flex;
			/*主軸方向居中,即水平居中*/
			justify-content: center;	
			/*側軸方向居中,即水平居中*/		
			align-items: center;
		}

		.box4 {
			width: 100px;
			height: 100px;
			background: pink;
		}

效果截圖
文章整理完了,歡迎測試代碼或下方評論哦~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章