P粉6158866602023-08-16 09:08:45
Since the width of the icon is always the same (2em
), we can use the ::after
pseudo-element as a "buffer" for space balancing on the right.
Set .button__icon
to the flexible layout flow. This is crucial when "pushing" other elements. Give it margin-right
to balance the left padding of the button.
Create a ::after
pseudo-element with flex-basis: calc(2em 20px)
. Among them, 2em
is the width of .button__icon
, and 20px
is the margin-right
of .button__icon
. This balances the left and right spaces when .button__text
is short.
Apply justify-content: space-between
to the parent element to help balance .button__icon
, .button__text
and ::after
When .button__text
is shorter.
Add flex-shrink: 999
, a huge shrink factor so that the layout engine will shrink ::after
elements first when .button__text
is longer.
*, *::before, *::after { box-sizing: border-box; } body { padding: 20px; min-height: 100vh; display: flex; flex-direction: column; } .grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; margin: auto 0; } .button { position: relative; display: flex; justify-content: space-between; align-items: center; cursor: pointer; outline: none; border: 1px solid #808080; padding: 20px; width: 100%; background-color: transparent; min-height: 80px; } .button::before { content: ""; width: 1px; position: absolute; top: 0; left: 50%; bottom: 0; background-color: red; } .button::after { flex: 0 999 calc(2em + 20px); content: ""; } .button__icon { flex-shrink: 0; margin-right: 20px; } .button__text { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; min-width: 0; text-align: center; border: 1px solid blue; }
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"/> <div class="grid"> <button class="button"> <i class="fa-solid fa-heart fa-2xl button__icon"></i> <span class="button__text"> 长文本,应该被截断 </span> </button> <button class="button"> <i class="fa-solid fa-thumbs-up fa-2xl button__icon"></i> <span class="button__text"> 中等长度 </span> </button> <button class="button"> <i class="fa-solid fa-house fa-2xl button__icon"></i> <span class="button__text"> 短 </span> </button> </div>