tft每日頭條

 > 生活

 > 怎麼讓div裡的div垂直居中

怎麼讓div裡的div垂直居中

生活 更新时间:2024-09-27 07:20:41

小編在做練習時遇到了一個問題:如何使一個div在另一個div裡面水平和垂直兩個方向全部居中。之前一般的情況都是一個div在另一個div裡面水平居中,直接使用margin:0 auto;即可解決。這次的情況第一次遇到,網上找了一些方法,親測有效,總結如下,将其放入一個頁面内了。

怎麼讓div裡的div垂直居中(一個div在另一個div内水平垂直兩方向居中的方法總結)1

HTML部分:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

</head>

<body>

<div class="parent1">

<div class="child1">方法一</div>

</div>

<div class="parent2">

<div class="child2">方法二</div>

</div>

<div class="parent3">

<div class="child3">方法三</div>

</div>

<div class="parent4">

<div class="child4">方法四</div>

</div>

</body>

</html>

怎麼讓div裡的div垂直居中(一個div在另一個div内水平垂直兩方向居中的方法總結)2

CSS部分:

<style>

*{margin: 0;padding: 0;}

/*方法一*/

.parent1{

width: 500px;height: 200px;

border: 4px solid #FF4500;

position: relative;

margin-top: 20px;margin-bottom: 20px;

}

.child1{

width: 200px;height: 150px;

margin: auto;position: absolute;

top: 0;right: 0;bottom: 0;left: 0;

background-color: #008B8B;

line-height: 150px;

text-align: center;

color: white;

}

/*方法二*/

.parent2{

width: 500px;height: 200px;

border: 4px solid #008B8B;

display: table-cell;

vertical-align: middle;

text-align: center;}

.child2{

width: 200px;height: 150px;

display: inline-block;

background-color: #008B8B;

line-height: 150px;color: white;

}

/*方法三*/

.parent3{

width: 500px;height: 200px;

border: 4px solid #008B8B;

margin-top: 20px;

display: flex;

justify-content: center;

align-items: center;

}

.child3{

width: 200px;height: 150px;

background-color: #008B8B;

line-height: 150px;

text-align: center;

color: white;

}

/*方法四 */

.parent4{

width: 500px;height: 200px;

border: 4px solid #FF4500;

position: relative;

margin-top: 20px;

}

.child4{

width: 200px;height: 150px;

background-color: #008B8B;

position: absolute;

top: 50%;left: 50%;

margin-left: -100px;

margin-top: -75px;

line-height: 150px;

text-align: center;

color: white;

}

</style>

最後效果圖如下:

怎麼讓div裡的div垂直居中(一個div在另一個div内水平垂直兩方向居中的方法總結)3

以上就是幾種簡單的居中方法,本文純屬練習,如有錯誤歡迎各位指出。

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved