這個問題在這里已經有了答案: 居中和右/左對齊其他 flexbox 元素 (10 個回答) 10 小時前關閉。
我有兩個元素:后退按鈕和標題。兩者都應該在同一行,后退按鈕應該左對齊,標題應該居中。
讓我們以這個例子為例:
<div class="wrapper">
<div class="button">
<button>Back</button>
<div class="headline">
<h2>Headline</h2>
</div>
</div>
</div>
我必須在 CSS 中做什么才能得到這個結果: 影像
我嘗試使用 Translate X,但當然這個解決方案不是回應式解決方案,這就是我為所有視口搜索一個的原因。
非常感謝,周末愉快!
uj5u.com熱心網友回復:
使用 flexbox 將包裝器中的所有內容居中,然后使用絕對定位將按鈕向左移動。
.wrapper {
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
button {
position: absolute;
left: 0;
}
<div class ="wrapper">
<button>Back</button>
<h2>Headline</h2>
</div>
uj5u.com熱心網友回復:
如果您知道它只是.wrapper容器內的這 2 個元素,那么這里有一個簡單的方法來做到這一點。
你要做的就是設定.wrapper到position: relative;,然后設定.button到position: absolute;這將允許您以定位.button的內部.wrapper,而不占用的div任何空間內。然后你設定.header為width: 100%;和text-align: center;
您需要使用移動設備,因為按鈕將跨越標題,此時我可能會堆疊元素以方便用戶單擊后退按鈕。
.wrapper {
position:relative;
background: #dedede;
}
.button {
position:absolute;
left:0;
top:50%;
transform:translate(0, -50%);
}
.headline {
width:100%;
text-align:center;
}
<div class ="wrapper">
<div class="button">
<button>Back</button>
</div>
<div class ="headline">
<h2>Headline</h2>
</div>
</div>
uj5u.com熱心網友回復:
此解決方案使用 css flex。
.wrapper{
display: flex;
flex-direction:row;
justify-content: flex-start;
align-items: baseline;
}
.headline{
display: flex;
flex-direction:row;
justify-content: center;
width:100%;
}
<div class ="wrapper">
<div class="button">
<button>Back</button>
</div>
<div class ="headline">
<h2>Headline</h2>
</div>
</div>
uj5u.com熱心網友回復:
<div class="wrapper">
<div class="button" style="float: left;">
<button>Back</button>
</div>
<div class="headline">
<h2 style="text-align: center;">Headline</h2>
</div>
</div>
實際上,這并不完全是您想要的。
但非常簡單和棘手的方式。
uj5u.com熱心網友回復:
使用 CSS 網格
這是有反應的!居中,
并且所有的 CSS 代碼都在父選擇器中!
- (使用flex,你會為這個簡單的事情寫很多)
解釋
place-items 用于居中。(就像寫 justify-.. 和 align-..)
grid template-column 用于指定網格應該如何(設定網格的方法有很多,但這是最短的)
實際上 AUTO 獲取元素的寬度并設定為它,但 1FR 得到
(AllWidthParent-AutoChildWidth)
代碼
<div class="wrapper">
<div class="button">
<button>Back</button>
</div>
<div class="headline">
<h2>Headline</h2>
</div>
</div>
<style>
.wrapper {
display: grid;
grid-template-columns: auto 1fr;
place-items: center;
width: 100%;
}
</style>
https://jsfiddle.net/laaouatni/vg5L38am/1/
uj5u.com熱心網友回復:
使用 css flex 的另一種簡單方法:
.wrapper {
display: flex;
align-items: center;
}
.headline {
margin: auto;
}
<div class ="wrapper">
<div class="button">
<button>Back</button>
</div>
<div class ="headline">
<h2>Headline</h2>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/387182.html
