最全的CSS盒子(div)水平垂直居中布局,對CSS 布局掌握程度決定你在 Web 開發中的開發頁面速度,
相對于螢屏

方法一:利用定位
<div ></div>
<style>
body {
background: green;
}
.box {
position: fixed;
top: 50%;
left: 50%;
margin: -150px 0 0 -150px;
width: 300px;
height: 300px;
background: orange;
}
</style>
設定 Position 為 fixed 定位,top 和 left 各設定 50%,margin 設定負的容器寬高的一半,
方法二:利用 transform
<div ></div>
<style>
body {
background: green;
}
.box {
position: fixed;
top: 50%;
left: 50%;
width: 300px;
height: 300px;
transform: translate(-50%, -50%);
background: orange;
}
</style>
設定 Position 為 fixed 定位,top 和 left 各設定 50%,transform 的 translate 設定上、左 -50%,
方法三:利用 margin auto
<div ></div>
<style>
body {
background: green;
}
.box {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 300px;
height: 300px;
background: orange;
}
</style>
設定 Position 為 fixed 定位,上、右、下、左設定為 0,margin 設定為 auto,
相對于父容器

方法一:利用定位
<div >
<div ></div>
</div>
<style>
.parent {
position: relative;
margin: 100px auto 0;
width: 500px;
height: 500px;
background: green;
}
.child {
position: absolute;
top: 50%;
left: 50%;
margin: -100px 0 0 -100px;
width: 200px;
height: 200px;
background: orange;
}
</style>
父容器設定為相對定位,子容器設定為絕對定位,top 和 left 各設定 50%,margin 設定負的子容器寬高的一半,
方法二:利用 transform
<div >
<div ></div>
</div>
<style>
.parent {
position: relative;
margin: 100px auto 0;
width: 500px;
height: 500px;
background: green;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background: orange;
}
</style>
父容器設定為相對定位,子容器設定為絕對定位,top 和 left 各設定 50%,transform 的 translate 設定上、左 -50%,
方法三:利用 margin auto
<div >
<div ></div>
</div>
<style>
.parent {
position: relative;
margin: 100px auto 0;
width: 500px;
height: 500px;
background: green;
}
.child {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 200px;
height: 200px;
background: orange;
}
</style>
父容器設定為相對定位,子容器設定為絕對定位,上、右、下、左設定為 0,margin 設定為 auto,
方法四:利用 flex
<div >
<div ></div>
</div>
<style>
.parent {
position: relative;
margin: 100px auto 0;
width: 500px;
height: 500px;
display: flex;
justify-content: center;
align-items: center;
background: green;
}
.child {
width: 200px;
height: 200px;
background: orange;
}
</style>
父容器 display 設定為 flex,水平垂直設定為居中,
方法五:計算父盒子與子盒子的空間距離
<div >
<div ></div>
</div>
<style>
.parent {
margin: 100px auto 0;
width: 500px;
height: 500px;
overflow: hidden;
background: green;
}
.child {
margin: 150px auto;
width: 200px;
height: 200px;
background: orange;
}
</style>
計算父盒子與子盒子的空間距離,
微信交流群
前端面試:劍指 Offer (3群)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/498866.html
標籤:Html/Css
上一篇:純前端實作-tab卡片化樣式切換
下一篇:sass變數的詳細使用
