Make flex container take width of content, not width 100%

我怕爱的太早我们不能终老 提交于 2019-11-27 15:33:43

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:

EDIT: Michael_B pointed out in his answer that inline-flex on the parent is the correct property for this use-case. I've updated my blog post accordingly.

It's not ideal, but if you wrap the button in a container that is inline-block, the button will scale naturally with the content, like so:

.button {
  /* other button styles */
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1.5rem 2rem;
}
<div style="display: inline-block;">
  <a class="button">Button</a>
</div>

You can then set the max-width on the container and the text will wrap to multiple lines, but retain the correct vertical centering.

I've detailed this in my most recent blog post: https://lukeboyle.com/css-buttons-solved-flexbox/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!