首页 > 解决方案 > 多行下划线按钮

问题描述

我在使用 box-shadow 为按钮文本添加下划线并将其包裹在多行时遇到问题。它应该只使用CSS来解决。

需要使用以下HTML(不能添加HTML标签、特殊字符等):

  <button class="button">
    <span class="button__inner">
      <span class="button__text">
        Button with very very very long example text
      </span>
      <svg class="button__icon" width="24" height="24" viewBox="0 0 24 24">
        <path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" />
      </svg>
    </span>
  </button>

视觉上应该是这样的!

要求:

  1. 使用box-shadow为多行文本添加下划线。
  2. 不要添加额外的 HTML(需要使用上面提供的 HTML 结构)。
  3. .button__inner 必须是 display: flex 或 inline-flex。
  4. 图标需要右对齐(在它自己的列中),垂直居中并且没有下划线。

.button {
  background: none;
  border: none;
  font-size: 12px;
  cursor: pointer;
}
.button:focus {
  outline: none;
}

.button__inner {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  text-align: left;
}

.button__text {
  box-shadow: inset 0 -1px currentColor;
}
.button:hover .button__text {
  box-shadow: none;
}

.button__icon {
  width: 1em;
  height: 1em;
}

p {
  font-size: 14px;
  line-height: 1.2em;
}
<div style="max-width: 200px">

  <p>
    Following button using correct HTML, however box-shadow does not underline correctly on multiple lines. The icon needs to be on the right in its own column so therefore adding display: inline; to .button__inner is not an option.
  </p>

  <button class="button">
    <span class="button__inner">
      <span class="button__text">
        Button with very very very long example text
      </span>
      <svg class="button__icon" width="24" height="24" viewBox="0 0 24 24">
        <path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" />
      </svg>
    </span>
  </button>

  <p>
    Below is the visually desired result, however it uses an additional span element. How to achieve this using just CSS and without altering the HTML?
  </p>

  <button class="button">
    <span class="button__inner">
      <span>
        <span class="button__text">
          Button with very very very long example text
        </span>
      </span>
      <svg class="button__icon" width="24" height="24" viewBox="0 0 24 24">
        <path d="M4,11V13H16L10.5,18.5L11.92,19.92L19.84,12L11.92,4.08L10.5,5.5L16,11H4Z" />
      </svg>
    </span>
  </button>
</div>

这甚至可能只使用 CSS 吗?

标签: cssbuttonflexboxunderlinebox-shadow

解决方案


在您的情况下使用text-decoration: underline代替是否有效box-shadow?像这个例子:https ://codepen.io/annaazzam/pen/PoZEJwX


推荐阅读