如何仅使用 CSS Flex 在一行上居中和右对齐
[英] How to Center and Right-align on a row with CSS Flex only
本文介绍了如何仅使用 CSS Flex 在一行上居中和右对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试了很多这样的变体,但无法让它工作.这是最后一次尝试:
.parent {显示:弹性;//对齐内容:居中;宽度:600px;背景颜色:黄色}.C {//弹性:1 1 0;//文本对齐:结束;左边距:自动;右边距:自动;背景颜色:青色;}.e {//弹性:1 1 0;//文本对齐:结束;背景颜色:灰色;}.bs {背景颜色:绿色;白颜色;宽度:70px;}
使用 html:
<div class="c"><button class="bs">OK</button><button class="bs">取消</button>
<div class="e"><button class="bs">帮助</button>
我知道如何通过在左侧放置一个可见性:隐藏"按钮并使用带有空格的 justify-content 来解决这个问题,但我想学习/知道如何仅使用 CSS 来做到这一点.
非常感谢您的建议.
解决方案
有不止一种方法可以做到这一点.
这里仅使用 CSS(没有额外的标记/隐藏元素)使用伪代码并使其和每个 按钮包装器 占据总宽度的 1/3,通过给它们 flex-based: 100%
然后默认的 flex-shrink: 1
将它们均等地收缩.
.parent {显示:弹性;宽度:600px;背景颜色:黄色}.parent::before, .c, .e {内容: '';弹性基础:100%;}.C {背景颜色:青色;文本对齐:居中;}.e {背景颜色:灰色;文本对齐:右;}.bs {背景颜色:绿色;白颜色;宽度:70px;}
<div class="c"><button class="bs">OK</button><button class="bs">取消</button>
<div class="e"><button class="bs">帮助</button>
<小时>
以上解决方案基于我在这里给出的答案:
这里还有另外 3 种方法,第一个示例也使用绝对定位无需任何额外标记即可解决此问题
Tried many variations like this, but could not get it to work. Here is the last attempt:
.parent {
display: flex;
//justify-content: center;
width: 600px;
background-color: yellow
}
.c {
//flex: 1 1 0;
//text-align: end;
margin-left: auto;
margin-right: auto;
background-color: cyan;
}
.e {
//flex: 1 1 0;
// text-align: end;
background-color: grey;
}
.bs {
background-color: green;
color: white;
width: 70px;
}
with html:
<div class="parent">
<div class="c">
<button class="bs">OK</button>
<button class="bs">Cancel</button>
</div>
<div class="e">
<button class="bs">Help</button>
</div>
</div>
I know how to solve this by placing a 'visibility: hidden' button on the left-hand side and use justify-content with space-between, but I want to learn/know how to do it using CSS only.
Would be grateful for advice.
解决方案
There is more than one way to do that.
Here with CSS only (no extra markup/hidden element) using a pseudo and make it and each button wrapper take 1/3 each of the total width, by giving them flex-basis: 100%
and then the default flex-shrink: 1
will shrink them equally.
.parent {
display: flex;
width: 600px;
background-color: yellow
}
.parent::before, .c, .e {
content: '';
flex-basis: 100%;
}
.c {
background-color: cyan;
text-align: center;
}
.e {
background-color: grey;
text-align: right;
}
.bs {
background-color: green;
color: white;
width: 70px;
}
<div class="parent">
<div class="c">
<button class="bs">OK</button>
<button class="bs">Cancel</button>
</div>
<div class="e">
<button class="bs">Help</button>
</div>
</div>
The above solution is based on the answer I gave here:
And here is 3 more ways, where the first sample also solve this without any extra markup using absolute positioning
这篇关于如何仅使用 CSS Flex 在一行上居中和右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!