Heim > Fragen und Antworten > Hauptteil
P粉6158866602023-08-16 09:08:45
由于图标的宽度始终相同(2em
),我们可以使用::after
伪元素作为右侧空间平衡的“缓冲区”。
将.button__icon
设置为弹性布局流。这在“推动”其他元素时至关重要。给它margin-right
来平衡按钮的左填充。
创建一个具有flex-basis: calc(2em + 20px)
的::after
伪元素。其中2em
是.button__icon
的宽度,20px
是.button__icon
的margin-right
。这样可以在.button__text
较短时平衡左右空间。
将justify-content: space-between
应用于父元素,以帮助平衡.button__icon
、.button__text
和::after
当.button__text
较短时。
添加flex-shrink: 999
,一个巨大的收缩因子,以便布局引擎在.button__text
较长时优先收缩::after
元素。
*, *::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>