這個問題在這里已經有了答案: 如何將元素水平居中 (123 個回答) 1 小時前關閉。
任何人都可以建議我在 CSS 中居中 div 的最快方法嗎?謝謝 !
<div = "wrap">
<div class = "container"></div>
</div>
uj5u.com熱心網友回復:
示例 1:中心 div 使用 margin-auto
https://i8pn0.csb.app/margin-auto-example.html
<div class="container">
<div class="child"></div>
</div>
.container {
width: 350px;
height: 200px;
outline: dashed 1px black;
}
.child {
width: 50px;
height: 50px;
background-color: red;
/* Center horizontally*/
margin: 0 auto;
}
示例 2:使用水平居中 Div display: flex
https://i8pn0.csb.app/flex-x.html
<div class="container">
<div class="child"></div>
</div>
.container {
margin: 25px;
width: 350px;
height: 200px;
/* Center child horizontally*/
display: flex;
justify-content: center;
}
.child {
width: 50px;
height: 50px;
background-color: red;
}
示例 3:使用垂直居中 Div display: flex
https://i8pn0.csb.app/flex-y.html
<div class="container">
<div class="child"></div>
</div>
.container {
margin: 25px;
width: 350px;
height: 200px;
outline: dashed 1px black;
/* Center vertically */
display: flex;
align-items: center;
}
.child {
width: 50px;
height: 50px;
background-color: red;
}
這些示例不是唯一的方法,而是最簡單的方法,其中一些僅適用于現代瀏覽器。
uj5u.com熱心網友回復:
使用display: flex.
.wrap {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: blue;
}
.container {
width: 100px;
height: 100px;
background-color: red;
}
<div class= "wrap">
<div class = "container"></div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/348949.html
標籤:javascript html css
