我有一個帶有側邊欄的頁面布局,旁邊有一個主要內容 div。在頁面的中途,我在 div(子)中有一個 div(父)。子 div 需要相對于螢屏而不是父 div 水平居中。
<div class="sidebar"></div>
<div class="main-content">
<div class="parent">
<div class="child"></div>
<div class="other-stuff"></div>
</div>
</div>
<style>
.parent{
width: 100px;
}
.child{
width: 200px;
}
</style>
我的第一個想法是使用絕對定位,如下所示:
.child{
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
text-align: center;
}
我在這里面臨的問題是,由于孩子被帶出檔案流,我必須彌補額外的空間。“其他東西”想向上移動以填補留下的空白。
除了用絕對定位推動 div 并添加額外的邊距/填充來彌補空間之外,是否有更好的方法來實作這一點,這樣較低的內容就不會出現?
我愿意放棄絕對定位——這只是我想到的第一件事。
uj5u.com熱心網友回復:
您可以使用 flexbox 將多個專案定位在一個容器中,并將子項從父 div 中剔除,這樣它就不會受到您所做的任何定位的影響。
*,
*::before,
*::after {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100vw;
}
.parent {
border: 1px solid black;
width: 100px;
height: fit-content;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
height: 100%;
gap: 2px;
}
.child {
display: block;
border: 1px solid black;
width: 200px;
height: fit-content;
}
.other-stuff {
display: block;
border: 1px solid black;
width: 200px;
height: fit-content;
}
<div class="sidebar"></div>
<div class="main-content">
<div class="parent">
I'm the Parent
</div>
<div class="container">
<div class="child">I'm the Child</div>
<div class="other-stuff">I'm the Other Stuff</div>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487774.html
標籤:javascript html css 响应式设计
