目录
一、定制设计利用伸缩盒flex定制设计使模块居中
1.伸缩盒与margin
定制设计给父元素设置为伸缩盒 dispaly:flex 子元素使用margin:auto
- <!DOCTYPE html>
- <html lang="en">
-
- <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>模块水平居</title>
- <style>
- /* 父元素设置flex 子元素margin:auto */
- .parent {
- width: 200px;
- height: 200px;
- background-color: aqua;
- display: flex;
- float: left;
- }
-
- .child {
- width: 100px;
- height: 100px;
- background-color: pink;
- margin: auto;
- }
- </style>
- </head>
-
- <body>
- <div class="parent">
- <div class="child"></div>
- </div>
- </body>
-
- </html>
2.使用grid与margin
给父元素设置display:grid 子元素使用 margin:auto
- .parent2 {
- width: 200px;
- height: 200px;
- display: grid;
- background-color: pink;
- }
-
- .child2 {
- width: 100px;
- height: 100px;
- background-color: blue;
- margin: auto;
- }
3.使用伸缩盒-content、align-items
使父元素变成伸缩盒,并设置设置主轴 、交叉轴居中
- .parent3 {
- width: 200px;
- height: 200px;
- display: flex;
- justify-content: center;
- align-items: center;
- background-color: rgb(0, 255, 47);
- float: left;
- }
-
- .child3 {
- width: 100px;
- height: 100px;
- background-color: pink;
- }
二、利用border和margin
给父元素设置 并给子元素设置
margin-left、margin-right、margin-top、margin-bottom
为子元素自身宽高的一半
- .parent4 {
- width: 200px;
- height: 200px;
- border: 1px solid red;
- background-color: rgb(0, 42, 255);
- }
-
- .child4 {
- width: 100px;
- height: 100px;
- margin: 50px;
- background-color: pink;
- }
三、通过box-sizing和padding
通过给父元素设置为边框盒子并且利用padding挤压,使子
- .parent5 {
- width: 200px;
- height: 200px;
- padding: 50px;
- box-sizing: border-box;
- background-color: rgb(225, 255, 0);
- }
-
- .child5 {
- width: 100px;
- height: 100px;
- background-color: pink;
- }
四、通过父相子绝
1.结合margin、top、right、left、bottom
父元素设置相对定位
子元素设置绝对定位,并且设置
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto
- .parent6 {
- width: 200px;
- height: 200px;
- position: relative;
- background-color: rgb(0, 255, 242);
-
- }
-
- .child6 {
- width: 100px;
- height: 100px;
- position: absolute;
- top: 0;
- right: 0;
- left: 0;
- bottom: 0;
- margin: auto;
- background-color: pink;
- }
2.结合top、left、margin
父元素设置相对定位
子元素设置绝对定位,并且设置
top: 50%;
left: 50%;
margin-left: -0.5宽px;
margin-top: -0.5高px;
- .parent7 {
- width: 400px;
- height: 400px;
- position: relative;
- background-color: rgb(222, 111, 94);
- }
-
- .child7 {
- width: 200px;
- height: 200px;
- background-color: pink;
- position: absolute;
- top: 50%;
- left: 50%;
- margin-left: -100px;
- margin-top: -100px;
- }