1、如何讓一個盒子水準垂直居中
1 //已知寬高
2 <div class="div1"></div>
3 <style>
4 .div1{
5 width:400px;
6 height:400px;
7 position:absolute;
8 left:50%;
9 top:50%
10 margin:-200px 0 0 -200px;
11 }
12 </style>
13
14 //未知寬高
15 <!DOCTYPE html>
16 <html lang="en">
17 <head>
18 <meta charset="UTF-8">
19 <title>Document</title>
20 <style>
21 .div1{
22 position: absolute;
23 left: 0;
24 top: 0;
25 bottom: 0;
26 right: 0;
27 margin: auto;
28 border: 1px solid #000;
29 width: 400px;
30 height: 400px;
31 }
32 </style>
33 </head>
34 <body>
35 <div class="div1"></div>
36 </body>
37 </html>
38
39 //未知寬高方法二:
40 <!DOCTYPE html>
41 <html lang="en">
42 <head>
43 <meta charset="UTF-8">
44 <title>Document</title>
45 <style>
46 .div1{
47 position: absolute;
48 left: 50%;
49 top: 50%;
50 transform: translate(-50%,-50%);
51 border: 1px solid #000;
52 width: 400px;
53 height: 400px;
54 }
55 </style>
56 </head>
57 <body>
58 <div class="div1"></div>
59 </body>
60 </html>
2、一個頁面上兩個div左右鋪滿整個浏覽器,要保證左邊的div一直為100px,右邊的div跟随浏覽器大小變化(比如浏覽器為500,右邊div為400,浏覽器為900,右邊div為800),請寫出大概的css代碼。
1 // 方法一:
2 <!DOCTYPE html>
3 <html lang="en">
4 <head>
5 <meta charset="UTF-8">
6 <title>Document</title>
7 <style>
8 .div1{
9 width: 100px;
10 height: 200px;
11 background-color: #ccc;
12 float: left;
13 }
14 .div2{
15 background-color: #ff0;
16 margin-left: 100px;
17 height: 200px;
18 }
19 </style>
20 </head>
21 <body>
22 <div class="div1"></div>
23 <div class="div2"></div>
24 </body>
25 </html>
26
27 //方法二:
28 <head>
29 <meta charset="UTF-8">
30 <title>Document</title>
31 <style>
32 .div{
33 display: flex;
34 flex-direction: row;
35 align-items: center;
36 }
37 .div1{
38 flex-basis: 100px;
39 background-color: #ccc;
40 height: 300px;
41 }
42 .div2{
43 background-color: #ff0;
44 height: 300px;
45 flex-grow: 1;
46 }
47 </style>
48 </head>
49 <body>
50 <div class="div">
51 <div class="div1"></div>
52 <div class="div2"></div>
53 </div>
54 </body>