是否可以根据css中最长的元素设置兄弟元素的宽度

时间:2018-04-19 23:40:02

标签: css

我要求将按钮的宽度设置为一行按钮中最长的兄弟。

规则:

  1. 按钮位于一行
  2. 按钮内容决定了按钮的宽度。
  3. 最长按钮应设置其他同级按钮的宽度
  4. 我已经尝试将flex: 1max/min-width一起使用但是这会打破规则2.我可以轻松地在js中做到这一点我想知道css是否可能单独使用?

    https://codepen.io/matthewharwood/pen/JvoVzE?editors=1100

    
    
    .link {
      height: 49px;
      padding: 0 24px;
      margin-right: 20px;
      background: pink;
    
      a {
    
        display: flex;
        align-items: center;
        line-height: 49px;
        justify-content: center;
      }
    }
    
    
    .container {
      width: 70%;
      margin: 0 auto;
      background: papayawhip;
      padding: 30px;
      display: flex;
    }
    
    .container2 {
      width: 70%;
      margin: 0 auto;
      background: orange;
      padding: 30px;
      display: flex;
      flex-wrap: wrap;
    }
    
    .container3 {
      width: 70%;
      margin: 0 auto;
      background: honeydew;
      padding: 30px;
      display: flex;
      flex-wrap: wrap;
    }
    
    <div class="container">
      <div class="link">
        <a href=""><span> 1 button</span></a>    
      </div>
      <div class="link">
        <a href=""><span> secondary button</span></a>    
      </div>
    </div>
    
    <div class="container2">
      <div class="link">
        <a href=""><span> 1 button</span></a>    
      </div>
      <div class="link">
        <a href=""><span> secondary button</span></a>    
      </div>
      <div class="link">
        <a href=""><span> third button</span></a>    
      </div>
    </div>
    
    
    <div class="container3">
      <div class="link">
        <a href=""><span> 1 button</span></a>    
      </div>
      <div class="link">
        <a href=""><span> 2 button</span></a>    
      </div>
    </div>
    &#13;
    &#13;
    &#13;

1 个答案:

答案 0 :(得分:1)

重要提示:以下解决方案是 hack

这里的想法是依靠方向列和inline-flex使所有元素等宽(最长的)然后我使用转换以恢复行方向。

我知道这是一个糟糕的黑客

.link {
  height: 49px;
  padding: 0 24px;
  background: pink;
  border:1px solid;
}
 

.container {
  padding: 30px;
  display: inline-flex;
  flex-wrap:wrap;
  flex-direction:column;
}
.link:nth-child(2) {
  transform:translate(100%,-100%);
}
.link:nth-child(3) {
  transform:translate(200%,-200%);
}
.link:nth-child(4) {
  transform:translate(300%,-200%);
}
<div class="container">
  <div class="link">
    <a href=""><span> 1 button</span></a>    
  </div>
  <div class="link">
    <a href=""><span> secondary button</span></a>    
  </div>
</div>
<br>
<div class="container">
  <div class="link">
    <a href=""><span> 1 button</span></a>    
  </div>
  <div class="link">
    <a href=""><span> secondary button</span></a>    
  </div>
  <div class="link">
    <a href=""><span> third button</span></a>    
  </div>
</div>
<br>
<div class="container">
  <div class="link">
    <a href=""><span> 1 button</span></a>    
  </div>
  <div class="link">
    <a href=""><span> 2 button</span></a>    
  </div>
</div>