Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Gray-Ice

个人博客兼个人网站

之前一直只知道如果要使div居中,需要添加宽和高并且margin 0 auto,今天看大佬的css3教程,发现了比较妙的方法。

利用Flex来使元素垂直水平居中

这个方法仅适用于父元素里只有一个子元素的情况(如果子元素是绝对定位的当我没说)。
代码如下:
html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./test.css">
</head>
<body>
<main>
<div>
</div>
</main>
</body>
</html>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
main{
width: 500px;
height: 500px;
display: flex;
/* 水平居中 */
justify-content: center;
/* 垂直居中 */
align-items: center;
}

div
{
height: 100px;
width: 100px;
}
div:nth-child(1)
{
background-color: #fab1a0;
}

利用transform属性来使元素垂直水平居中

这里父元素和子元素都使用了绝对定位。但是其实父元素不用绝对定位也可以。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./test.css">
</head>
<body>
<main>
<div>
</div>
</main>
</body>
</html>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
main{
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 500px;
// 第一个参数是相对于x轴位移的数据,第二个参数是相对于y轴位移的数据
transform: translate(-50%, -50%);
border: 1px solid black;
}

div
{
height: 100px;
width: 100px;
position: absolute;
top: 50%;
left: 50%;
// 第一个参数是相对于x轴位移的数据,第二个参数是相对于y轴位移的数据。位移的百分比是相对于该元素自身的。
transform: translate(-50%, -50%);
}
div:nth-child(1)
{
background-color: #fab1a0;
}

手动计算偏移量

这个方法有点不太方便,因为你要手动计算出偏移量,所以不是很推荐。
那么代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./test.css">
</head>
<body>
<main>
<div>
</div>
</main>
</body>
</html>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
main{
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 500px;
margin-left: -250px;
margin-top: -250px;
border: 1px solid black;
}

div
{
height: 100px;
width: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
div:nth-child(1)
{
background-color: #fab1a0;
}

那么本篇完。

评论



愿火焰指引你