【问题标题】:Two equal width columns (where the width is set by the longest one) and a third one fills the remaining space两个等宽的列(宽度由最长的一个设置),第三个填充剩余空间
【发布时间】:2020-03-26 23:47:23
【问题描述】:

我想制作这样的布局,如果可能的话,使用 CSS Grid,但对其他可能性持开放态度:

基本上,我想要一个包含 3 个元素(输入、btn1、btn2)的容器.grid。首先,btn1 和 btn2 的宽度应该相同,并且取决于哪个元素需要更多空间(即更长的内容)。在那之后,剩下的元素(输入)应该把剩下的全部拿走。我想出了这个 sn-p 但肯定它不能工作。

.grid {
  display: grid;
  grid-template-columns: auto 1fr 1fr;
}
<div class="grid">
  <input />
  <button>Foo</button>
  <button>Bar Bar Bar</button>
</div>

什么是仅使用 CSS 实现此目的的好方法?

【问题讨论】:

  • 我对可能的答案很感兴趣,但如果不将两个按钮嵌套在一个共享的祖先中,我个人无法看到这是如何实现的(演示:jsfiddle.net/davidThomas/ph7ub2nk)。
  • @DavidsaysreinstateMonica 这确实是我认为答案会使用的,但我仍然希望看到没有它的聪明解决方案。
  • javascript 需要检查按钮的宽度才能开始,平均的 CSS 折衷可能是:grid-template-columns: minmax(auto,3fr) 1 fr 1fr; 这是 CSS 会在这里做的最多的事情。
  • @DavidsaysreinstateMonica 那个演示很聪明,即使有嵌套!
  • js 想法:codepen.io/gc-nomade/pen/XWbyEZm 如果结构保持不变;)(这里没有javascript标签,所以只是评论)

标签: html css css-grid


【解决方案1】:

为按钮使用嵌套的网格容器。

.grid {
  display: grid;
  grid-template-columns: 1fr auto; /* see note 1 */
}

.button-container {
  display: grid;
  grid-template-columns: 1fr 1fr; /* see note 2 */
}
<div class="grid">
  <input />
  <div class="button-container">
    <button>Foo</button>
    <button>Bar Bar Bar</button>
  </div>
</div>
<br>
<div class="grid">
  <input />
  <div class="button-container">
    <button>Foo</button>
    <button>Bar Bar Bar Bar Bar Bar</button>
  </div>
</div>
<br>
<div class="grid">
  <input />
  <div class="button-container">
    <button>Foo</button>
    <button>Bar Bar Bar Bar Bar Bar Bar Bar Bar</button>
  </div>
</div>

注意事项:

  1. 第一列上的1fr 占用了所有可用的水平空间,尽可能将第二列固定在右侧。

  2. 嵌套列上的1fr 1fr 会导致子容器中的水平空间被均分,无论内容宽度如何。

【讨论】:

    【解决方案2】:

    这是一个 hack(是的 hack!),它依赖于您知道容器宽度这一事实。

    在下面,我将考虑一个整页容器(宽度使用100vw 定义)

    .grid {
      display: grid;
      margin:50px 5px;
      grid-template-columns:1fr auto;
    }
    /* they will overlap so the longest one will define the size of auto*/
    button {
      grid-column:2;
      grid-row:1;
    }
    
    /* we translate the first one to disable the overlap*/
    button:first-of-type {
      transform:translateX(-100%);
    }
    
    input {
      /* 100vw - 10px = width of the grid container 
         100% is the width of the 1fr
         ((100vw - 10px) - 100%) will be the width of the buttons
      */
      width:calc(100% - ((100vw - 10px) - 100%));
      box-sizing:border-box;
    }
    
    body {
     margin:0;
    }
    <div class="grid">
      <input >
      <button>Foo</button>
      <button>Bar Bar Bar</button>
    </div>

    【讨论】:

    • 这既美丽又可怕(只是在努力了解它如何/为什么起作用)。 :)
    • 虽然我不会在我的代码中使用它,但你真的让我吃惊!有时我想知道人们怎么能想出像这样美丽可怕的东西(/s)
    猜你喜欢
    • 2010-11-18
    • 1970-01-01
    • 2012-02-21
    • 2013-09-28
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    相关资源
    最近更新 更多