I have the following code that behaves quite weird. My expectation is the button width change to let the contents appear inside the button.
Unfortunately the text is overflowing the button and I cannot find how to fix it.
Does anyone see what I do wrong with it? I’ve tried several different options and none of them worked.
:root {
--green: hsl(150.22deg 60.35% 44.51%);
--green-dark: hsl(150.22deg 60.35% 35%);
--green-light: hsl(148.89deg 87.1% 93.92%);
--blue: hsl(202.86deg 77.78% 15.88%);
}
.btn {
text-decoration: none;
display: inline-flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: center;
justify-content: space-between;
white-space: nowrap;
border-radius: 9999px;
font-weight: 600;
text-transform: capitalize;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
padding-top: 0.5rem;
padding-bottom: 0.5rem;
padding-left: 1rem;
padding-right: 1rem;
font-size: 1rem;
line-height: 1.5rem;
}
.btn--green {
background-color: var(--green);
--tw-text-opacity: 1;
color: rgb(255 255 255 / var(--tw-text-opacity));
transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 300ms;
transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
}
.btn:has(svg) {
gap: 0.75rem;
}
.btn svg {
display: block;
max-height: 16px;
max-width: 16px;
flex-shrink: 0;
fill: #fff;
}
<a href="#" class="btn btn--green">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128">
<path d="M37 33a3 3 0 0 0 2.2-1L61 10.2V91a3 3 0 0 0 6 0V10.2L88.8 32a3 3 0 0 0 4.2-4.2L66.1.8a3 3 0 0 0-.4-.3l-.3-.1a3 3 0 0 0-.3-.2 3 3 0 0 0-.3 0l-.2-.1a3 3 0 0 0-1.2 0h-.2a3 3 0 0 0-.3.1 3 3 0 0 0-.3.2l-.3.1a3 3 0 0 0-.4.4L35 27.8a3 3 0 0 0 2.1 5.1Z"></path>
<path d="M125 88a3 3 0 0 0-3 3v22a9 9 0 0 1-9 9H15a9 9 0 0 1-9-9V91a3 3 0 0 0-6 0v22a15 15 0 0 0 15 15h98a15 15 0 0 0 15-15V91a3 3 0 0 0-3-3Z"></path>
</svg>
Button With Icon
</a>
<br>
<a href="#" class="btn btn--green">
Button Without Icon
</a>
2
Answers
Please let me know if this is what you wanted to achieve
The button doesn’t have explicit width and the SVG neither. The SVG needs to have some intrinsic width. If you compare button widths from button 1 and button 2 in output from following demo. Then you’ll see the buggy button is
16px
short.The flex box doesn’t have any way of knowing button width (max-width) doesn’t count because all the sizing algorithms use
width
and notmax-width
for calculations. You need to set explicitwidth
either on<svg>
or in.btn svg
.I suggest using
1 rem
as width on SVG because it is relative to the font size.