如何将Bootstrap卡片按钮设为内容自适应宽度?附Handlebars代码
Got it, let's fix that button width issue! The problem here is likely either a Bootstrap class forcing full width or the button sitting in a flex container that's stretching it. Here are a few straightforward solutions tailored to your Handlebars code:
1. Remove btn-block (if present)
Bootstrap's btn-block class explicitly makes buttons take up 100% of their parent container's width. If your button accidentally has this class, removing it will revert the button to its default inline-block behavior, which wraps only its content:
<a href="/ideas/edit/{{id}}" class="btn btn-primary">Edit</a>
2. Handle Flex Container Stretching
If your card-body is using flex layout (via Bootstrap's d-flex class), buttons inside will automatically stretch to fill the container width. To prevent this, add Bootstrap's align-self-start class to the button to keep it sized to its content:
<a href="/ideas/edit/{{id}}" class="btn btn-primary align-self-start">Edit</a>
3. Custom CSS for Explicit Control
If the above methods don't work, you can add a custom CSS class to force the button to wrap its content. First, add this CSS to your stylesheet:
.btn-content-wrap { width: fit-content; display: inline-block; /* Optional: Add some horizontal padding if needed */ padding-left: 1rem; padding-right: 1rem; }
Then update your Handlebars button to use this class:
<a href="/ideas/edit/{{id}}" class="btn btn-primary btn-content-wrap">Edit</a>
All these methods will make your "Edit" button only take up as much space as its text and padding need, instead of spanning the full card width.
内容的提问来源于stack exchange,提问作者Muneeb Ejaz

