我正在尝试在CSS中实现某个列布局.我已经探索过使用Flexbox以及CSS Grid,但是我所谈过的所有同行都无法找到一种方法来实现这项功能.我知道我可以使用
JavaScript实现它,但我想尽可能避免这种情况.
我想创建一个三列的布局.第1列和第3列的宽度应匹配(由较长列的内容定义),第2列应缩小并增长以允许内容适合(但不能展开以填充父容器).
绘制一张我想要的图片有点困难,所以请看看这个CodePen,我已经分解了基本代码并展示了我想要的模拟示例.
这是HTML结构
<div class="container">
<div class="col col--Z">Let's match cols, but also collapse!</div>
<div class="col col--Y">No! 😣 Let me shrink!</div>
<div class="col col--Z">Yes!</div>
</div>
这是SCSS结构
.container {
display: grid;
justify-content: center;
grid-template-columns: 1fr auto 1fr;
.col {
padding-left: 6px;
padding-right: 6px;
&.col--Z {
background: rgba(0,255,55,0.2);
}
&.col--Y {
background: rgba(0,0,255,0.2);
}
}
}
* {
font-family: 'Arial', Sans-Serif;
}
.container {
display: grid;
justify-content: center;
grid-template-columns: 1fr auto 1fr;
}
.container .col {
padding-left: 6px;
padding-right: 6px;
}
.container .col.col--Z {
background: rgba(0, 255, 55, 0.2);
}
.container .col.col--Y {
background: rgba(0, 0, 255, 0.2);
}
.container-faked {
display: grid;
justify-content: center;
grid-template-columns: 260px auto 260px;
}
.container-faked .col {
padding-left: 6px;
padding-right: 6px;
}
.container-faked .col.col--Z {
background: rgba(0, 255, 55, 0.2);
}
.container-faked .col.col--Y {
background: rgba(0, 0, 255, 0.2);
}
<!-- This is the actual code -->
<h1>CSS Grid Attempt (actual code)</h1>
<div class="container">
<div class="col col--Z">Let's match cols, but also collapse!</div>
<div class="col col--Y">No! 😣 Let me shrink!</div>
<div class="col col--Z">Yes!</div>
</div>
<br>
<hr>
<br>
<!-- This is the objective, mocked up! -->
<h1>CSS Grid Attempt (faked example)</h1>
<div class="container-faked">
<div class="col col--Z">Let's match cols, but also collapse!</div>
<div class="col col--Y">No! 😣</div>
<div class="col col--Z">Yes!</div>
</div>
CodePen既包含基本代码(不工作),也包含我想要实现的模拟示例,但使用固定像素值来模拟等宽列.
https://codepen.io/seanmaisch/pen/MZdqoW
最佳答案 您可以使用display:inline-grid根据内容制作网格容器宽度.要使它居中,你可以使用一些.wrapper块.
* {
font-family: 'Arial', Sans-Serif;
}
.wrapper {
display: flex;
justify-content: center;
}
.container {
display: inline-grid;
grid-template-columns: 1fr auto 1fr;
}
.container .col {
padding-left: 6px;
padding-right: 6px;
}
.container .col.col--Z {
background: rgba(0, 255, 55, 0.2);
}
.container .col.col--Y {
background: rgba(0, 0, 255, 0.2);
}
<div class="wrapper">
<div class="container">
<div class="col col--Z">Let's match cols, but also collapse!</div>
<div class="col col--Y">No! 😣 Let me shrink!</div>
<div class="col col--Z">Yes!</div>
</div>
</div>