在下面的示例中,我有一个具有以下样式的按钮......
.button-flexbox-approach {
/* other button styles */
display: flex;
justify-content: center;
align-items: center;
padding: 1.5rem 2rem;
}
http://codepen.io/3stacks/pen/JWErZJ http://codepen.io/3stacks/pen/JWErZJ
但它会自动缩放到 100%,而不是内容的宽度。您可以设置明确的宽度,但这不允许文本自然换行。
如何制作一个按钮,其内部文本以 Flexbox 为中心,但不会增长以适应容器的大小?
.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>
代替display: flex
在容器上,使用display: inline-flex
.
这会将容器从块级(采用其父级的完整宽度)切换到内联级(采用其内容的宽度)。
这种尺寸调整行为类似于display: block
vs. display: inline-block
.
相关问题及解决方案参见:
- 使弹性项目采用内容宽度,而不是父容器的宽度 https://stackoverflow.com/q/40141163/3597276
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)