前言
css
布局是前端開發(fā)必須掌握的基本內容看尼,前端學習之css
基本布局整理歪玲。
基本布局
左右布局
div
結構:
<div class="parent">
<div class="son1"></div>
<div class="son2"></div>
</div>
float浮動
左右布局一般為********子元素********添加********浮動********float
站绪,在********父元素********添加clearfix
惧盹;
//html
<div class="parent clearfix">
<div class="son1"></div>
<div class="son2"></div>
</div>
//css
.son1 ,
.son2 {
float: left;
}
position定位
使用position
定位絮记,********父元素********添加relative
相對定位鸣皂,********子元素********添加absolute
絕對定位抓谴;
//css
.parent{
position:relative;
}
.son1{
position:absolute;
left:0;
top:0;
}
.son2{
position:absolute;
left:200px;
top:0;
}
左中右布局
這個有很多種方式,最簡單的float + absolute
就可以實現寞缝;
div
結構:
<div class="parent">
<div class="son1"></div>
<div class="son2"></div>
<div class="son3"></div>
</div>
css布局:
.son1{
width: 200px;
height:100%;
float: left;
}
.son2{
position: absolute;
top:0;
bottom:0;
left:200px;
right: 300px;
}
.son3{
height:100%;
width: 300px;
float: right;
}
水平居中
寬度固定的水平居中
這個直接margin:0 auto;
.parent{
height: 200px;
width: 400px;
margin: 0 auto;
}
寬度不固定的水平居中
- ********子元素********添加
display:inline-block
癌压,********父元素********添加center
.parent{
text-align: center;
}
.son{
display: inline-block;
vertical-align: top;
}
因為son
添加了inline-block
后,會與父元素div
下邊框有間隙荆陆,所以添加vertical-align: top
滩届;
-
position
相對定位。父元素相對頁面絕對布局被啼,子元素相對父元素布局
//相對定位要添加float浮動
.parent{
position: absolute;
left: 50%;
}
.son{
position: relative;
left: -50%;
}
- 使用
width:fit-content
和margin
配合
.son{
width: fit-content;
margin: 0 auto;
}
垂直居中
高度固定的垂直居中
高度和行高一樣就居中了啊
.son{
height: 999px;
line-height: 999px;
}
高度不固定的垂直居中
-
position
絕對定位帜消。
parent{
position: relative;
}
son{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
margin
.parent{
position:fixed;
width:100%;
height:100%;
top:0;
left:0;
}
.son{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
width:50%;
height:50%;
margin:auto;
}
- flex布局
parent{
display:flex;
align-items:center;
}
其他小技巧
合理使用偽元素(如::after棠枉、::before)
color: inherit
顏色繼承父元素:nth-child(n)
選擇器匹配屬于其父元素的第n
個子元素,不論元素的類型