首页 > 解决方案 > 两个等宽的列(宽度由最长的一个设置),第三个填充剩余空间

问题描述

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

在此处输入图像描述

基本上,我想要一个.grid包含 3 个元素(输入、btn1、btn2)的容器。首先,btn1 和 btn2 的宽度应该相同,由需要更多空间(即更长的内容)的元素决定。在那之后,剩余的元素(输入)应该取走所有剩下的东西。我想出了这个片段,但肯定它不能工作。

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

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

标签: htmlcsscss-grid

解决方案


这是一个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>


推荐阅读