【问题标题】:How to make flex children have equal widths and at the same time not larger than its contents?如何使 flex 子项具有相等的宽度并且同时不大于其内容?
【发布时间】:2019-01-07 14:46:48
【问题描述】:

我有以下代码:

.parent {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.firstChild {
  flex: 1;
  text-align: left;
}

.lastChild {
  flex: 1;
  text-align: right;
}
<div class="parent">
  <a href="#" class="firstChild">A very loooooooooooooooooong link</a>
  <span>Work</span>
  <span class="lastChild">Other</span>
</div>

Complete fiddle here

问题是:第一个 flex 子(长链接)元素大于其内容(因为 flex-grow)。因此,当用户单击其文本旁边时,它也会激活链接。

我们在这里使用了 flex-grow 以使 1. 和 3. 子元素的宽度相等,因此 2. 元素可以几乎 - 站在中间(因为 flex 子元素的宽度变化很大)。我如何在不使用 flex-grow 的情况下实现这一目标?或者换句话说,我如何保证链接的宽度等于其文本的宽度?

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    只需使用这个。

    <div class="parent">
    <div class="firstChild">
    <a href="#" class="">A very looooooooooooooooooooong link</a>
    </div>
     
     <div>
       <span>Work</span>
     </div>
      <div class="lastChild">
       <span>Other</span>
     </div>
    </div>

    【讨论】:

      【解决方案2】:

      用一个额外的span.firstChild包装它:

      .parent {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
      }
      
      .firstChild {
        flex:1;
        text-align:left;
      }
      
      .lastChild {
        flex:1;
        text-align:right;
      }
      
      /* for overview */
      a {
        border: 1px solid red;
      }
      <div class="parent">
       <span class="firstChild">
        <a href="#">A very loooooooooooooooooong link</a>
       </span>
       <span>Work</span>
       <span class="lastChild">Other</span>
      </div>

      【讨论】:

      • 谢谢 :) 其实很简单。丹麦人以 1 分钟获胜。差异对不起:)
      • 嘿,这不是比赛。乐于助人:)。
      【解决方案3】:

      试试这个:

      .parent {
        display: grid;
        align-items: center;
        justify-items: start;
        grid-auto-flow: column;
        justify-content: space-between;
        grid-template-columns: repeat(3, 1fr);
        justify-items: center;
      }
      <div class="parent">
       <a href="#" class="firstChild">A very looooooooooooooooooooong link</a>
       <div>
         <span>Work</span>
       </div>
        <div class="lastChild">
         <span>Other</span>
       </div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 2019-09-12
        • 2017-07-20
        • 1970-01-01
        • 2022-01-17
        • 2018-07-19
        相关资源
        最近更新 更多