问题描述
在下面的例子中,我有一个按钮,样式如下:.button-flexbox-approach {
/ *其他按钮样式* /
display:flex;
justify-content:center;
align-items:center;
填充:1.5rem 2rem;
但它会自动缩放到100%内容的宽度。你可以设置一个明确的宽度,但不允许你的文本自然地包装。
如何制作一个按钮,其中的内部文本以flexbox为中心,但不会增长以适应容器的大小?
这将容器从块级别切换到内联级别(取其内容的宽度)。
这个尺寸行为类似于 display:block vs display:inline-block $ c
对于相关的问题和解决方案,请参阅:
In the below example, I have a button with the following styles...
.button-flexbox-approach { /* other button styles */ display: flex; justify-content: center; align-items: center; padding: 1.5rem 2rem; }
http://codepen.io/3stacks/pen/JWErZJ
But it automatically scales to 100% instead of the width of the content. You can set an explicit width, but then that doesn't allow your text to wrap naturally.
How can I make a button that has the inner text centered with flexbox, but doesn't grow to fit the size of the container?
.container { width: 100%; height: 100%; } .button { /* Simply flexing the button makes it grow to the size of the container... How do we make it only the size of the content inside it? */ display: flex; justify-content: center; align-items: center; -webkit-appearance: none; border-radius: 0; border-style: solid; border-width: 0; cursor: pointer; font-weight: normal; line-height: normal; margin: 0; position: relative; text-align: center; text-decoration: none; padding: 1rem 2rem 1.0625rem 2rem; font-size: 1rem; background-color: #D60C8B; border-color: #ab0a6f; color: #fff; } .one { margin-bottom: 1rem; } .two { /* You can put an explicit width on that, but then you lose the flexibility with the content inside */ width: 250px; }
<div class="container"> <p> Button one is flexed with no width and it grows to the size of its container </p> <p> <a class="button one" href="#">Button</a> </p> <p> Button two is flexed with an explicit width which makes it smaller, but we have no flexibility for changing the content </p> <p> <a class="button two" href="#">Button 2</a> </p> </div>
Instead of display: flex on the container, use display: inline-flex.
This switches the container from block-level (which takes the full width of its parent) to inline-level (which takes the width of its content).
This sizing behavior is similar to display: block vs. display: inline-block.
For a related problem and solution see:
这篇关于使flex容器占用内容的宽度,而不是宽度的100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!