我有一堆按钮,我希望它们都具有相同的宽度而不必设置特定的宽度,所以自然地,您希望 all 按钮的宽度采用最广泛的元素,但是我很难用flex做到这一点,因为似乎只希望它们都是100%;我还用锚定器周围的包装纸进行了尝试,但这没有帮助,因为按钮的宽度各不相同。
代码笔: https://codepen.io/gutterboy/pen/MZWroj?editors=1100
因此,在该示例中,所有按钮应与“地面保管”的自然宽度匹配。
HTML:
<div class="container">
<div class="row">
<div class="offset-md-4 col-md-4">
<div class="buttons">
<a href="" class="btn alt">Plumbing</a>
<a href="" class="btn alt">Electrical</a>
<a href="" class="btn alt">Groundskeeping</a>
<a href="" class="btn alt">Construction</a>
<a href="" class="btn alt">Cleaning</a>
<a href="" class="btn alt">Security</a>
<a href="" class="btn alt">Trades Assistant</a>
<a href="" class="btn alt">General Duties</a>
</div>
</div>
</div>
</div>
CSS:
.buttons {
display: flex;
flex-direction: column;
padding: 15px;
background-color: gray;
.btn {
display: block;
margin-bottom: 11px;
&:last-child {
padding-bottom: 21px;
}
}
}
a.btn {
display: inline-block;
text-align: center;
height: 35px;
padding: 0 20px;
min-width: 128px;
font-weight: bold;
color: #fff;
background-color: orange;
border: 2px solid #000;
white-space: nowrap;
text-decoration: none;
}
在Flex或其他任何方式上可以完成此操作吗?
答案 0 :(得分:1)
您几乎不错,应该使用inline-flex
而不是flex
来具有“缩小以适应”的行为,因此最大的按钮将定义容器的宽度,默认情况下所有元素都是伸展到那个宽度:
.container {
margin-top: 15px;
text-align:center;
}
.buttons {
display: inline-flex;
flex-direction: column;
padding: 15px;
background-color: gray;
}
.buttons .btn {
display: block;
margin-bottom: 11px;
}
.buttons .btn:last-child {
padding-bottom: 21px;
}
a.btn {
display: inline-block;
text-align: center;
height: 35px;
padding: 0 20px;
min-width: 128px;
font-weight: bold;
color: #fff;
background-color: orange;
border: 2px solid #000;
white-space: nowrap;
text-decoration: none;
}
<div class="container">
<div class="buttons">
<a href="" class="btn alt">Plumbing</a>
<a href="" class="btn alt">Electrical</a>
<a href="" class="btn alt">Groundskeeping</a>
<a href="" class="btn alt">Construction</a>
<a href="" class="btn alt">Cleaning</a>
<a href="" class="btn alt">Security</a>
<a href="" class="btn alt">Trades Assistant</a>
<a href="" class="btn alt">General Duties</a>
</div>
</div>