寫在前面的話:
在編寫html頁面的時候最??紤]的就是應(yīng)該是類的命名吧,其次就是該使用怎樣的布局方式使得頁面的適應(yīng)性比較高。居中在頁面布局中是最常用的布局之一了,根據(jù)度娘和本人開發(fā)經(jīng)驗總結(jié)出以下三種可用性比較高的居中方案,如有補(bǔ)充請在評論區(qū)留言指正。話不多說開搞!
正文
1.第一種:
使用 position:absolut+transform 實現(xiàn)垂直居中
<style>
.parent{
width: 100%;
height: 500px;
border: #008000 1px solid;
position: relative;
margin-bottom: 10px;
}
.content{
width: 100px;
height: 100px;
border: #ccc 1px solid;
}
.content1{
background-color: #1effcc;
position: absolute;
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
}
</style>
<div class="parent">
<div class="content content1">
position:absolut+transform
</div>
</div>
效果圖如下:
1285342-20200811150818882-2102128730.png
重點是將父類元素的position設(shè)置為relative,再將子元素的position設(shè)置為absolute,之后進(jìn)行絕對定位(top:50%,left:50%),最后通過使用transform對元素進(jìn)行修正位置,使得元素處于居中的位置。
2.第二種:
<style>
body{
height: 100%;
width: 100%;
overflow-x: hidden;
}
.parent{
width: 100%;
height: 500px;
border: #008000 1px solid;
position: relative;
margin-bottom: 10px;
}
.content{
width: 100px;
height: 100px;
border: #ccc 1px solid;
}
.content2{
background-color: #11d5ff;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
<div class="parent">
<div class="content content2">
<span>
position:
absolut
+
margin
</span>
</div>
</div>
該方法同樣可以得到居中的效果,其重點也是父類元素(.parent)的元素position設(shè)置為relative,子類設(shè)置為absolute,與第一種方式不同的是使用margin:auto 屬性使得元素居中,值得一提的是top屬性和bottom屬性的值要一樣,right和left的值要一樣,這樣才能保證元素
居中,為了方便都設(shè)置為0。
3.第三種:
使用vertical-align: middle;display: inline-block;
<style>
body{
height: 100%;
width: 100%;
overflow-x: hidden;
}
.parent{
width: 100%;
height: 500px;
border: #008000 1px solid;
position: relative;
margin-bottom: 10px;
}
.content{
width: 100px;
height: 100px;
border: #ccc 1px solid;
background: #FFA500;
}
.parent2{
text-align: center;
line-height: 500px;
}
.content5{
vertical-align: middle;
display: inline-block;
line-height: 18px;
}
</style>
<div class="parent parent2">
<div class="content content5">
vertical-align: middle;
display: inline-block;
</div>
</div>
將子類元素(.content)display設(shè)置inline-block 父類元素使用line-height的方式(設(shè)置line-height的高度為.parent 父類元素的高度)使得在垂直上對齊。
3.第四種:
使用flex布局
<style>
body{
height: 100%;
width: 100%;
overflow-x: hidden;
}
.parent{
width: 100%;
height: 500px;
border: #008000 1px solid;
position: relative;
margin-bottom: 10px;
}
.content{
width: 100px;
height: 100px;
border: #ccc 1px solid;
background: #FFA500;
}
.parent2{
display: flex;
align-items: center;
justify-content: center;
line-height: 500px;
}
.content5{
vertical-align: middle;
display: inline-block;
line-height: 18px;
}
</style>
<div class="parent parent2">
<div class="content content5">
display: flex;
align-items: center;
justify-content: center;
</div>
</div>