在CSS Grid中将列宽设置为内容长度

mr.*_*ris 13 css css3 css-grid

我查看了文档,但没有找到这样的属性.我想使用css网格将一列中的所有单元格调整到其内容宽度.

对于第一种情况,我应该为容器应用此属性: grid-template-columns: auto auto;

但是我应该为第二种情况做些什么呢?

在此输入图像描述

Dan*_*eld 17

在网格容器上设置以下内容:

grid-template-columns: auto 1fr;
Run Code Online (Sandbox Code Playgroud)

这将第一列的宽度设置为等于该中最宽项目的宽度,并将第二列的宽度设置为网格的剩余宽度。

要右对齐第二列的内容,我们可以简单地使用 text-align: right

span:nth-child(2n) {
  text-align: right;
}
Run Code Online (Sandbox Code Playgroud)

grid-template-columns: auto 1fr;
Run Code Online (Sandbox Code Playgroud)
span:nth-child(2n) {
  text-align: right;
}
Run Code Online (Sandbox Code Playgroud)

注意:设置列宽min-content有点更激进:) 并将列的宽度设置为列中最大单词的宽度。

div {
  display: grid;
  grid-template-columns: auto 1fr;
}
span {
  padding: 0.5em;
}
span:nth-child(2n) {
  text-align: right;
}
span:nth-child(1) {
  background-color: beige; /* colors for demo */
}
span:nth-child(2) {
  background-color: wheat;
}
span:nth-child(3) {
  background-color: lightgreen;
}
span:nth-child(4) {
  background-color: salmon;
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <span>some content here</span>
  <span>content</span>
  <span>cell3</span>
  <span>cell4</span>
</div>
Run Code Online (Sandbox Code Playgroud)


Mic*_*l_B 16

要使所有列"缩小到适合",请使用内联级网格容器:

article {
  display: inline-grid;
  grid-template-columns: auto auto;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }
Run Code Online (Sandbox Code Playgroud)
<article>
  <section>content</section>
  <section>content</section>
  <section>cell3</section>
  <section>cell4</section>
</article>
Run Code Online (Sandbox Code Playgroud)

要使列"缩小到适合",请使用min-content:

article {
  display: grid;
  grid-template-columns: min-content auto;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }
Run Code Online (Sandbox Code Playgroud)
<article>
  <section>content</section>
  <section>content</section>
  <section>cell3</section>
  <section>cell4</section>
</article>
Run Code Online (Sandbox Code Playgroud)

auto1fr也将工作,因为fr将消耗上线的所有可用空间,折叠另一列尽可能:

article {
  display: grid;
  grid-template-columns: auto 1fr;
}

/* non-essential demo styles */
article { background-color: black; border: 1px solid black; }
section { background-color: white; border: 1px solid black; }
Run Code Online (Sandbox Code Playgroud)
<article>
  <section>content</section>
  <section>content</section>
  <section>cell3</section>
  <section>cell4</section>
</article>
Run Code Online (Sandbox Code Playgroud)

规格中的更多信息: