gpt4 book ai didi

css - 如何使用 css 列将列宽调整为内容大小?

转载 作者:行者123 更新时间:2023-11-28 12:04:24 25 4
gpt4 key购买 nike

我正在使用 css 列(不是表格)来创建一个跨越 3 列的列表,如下所示:

HTML

<ul>
<li>- Item 1 - this is the item's name here.</li>
<li>- Item 2</li>
<li>- Item 3</li>
<li>- Item 4</li>
<li>- Item 5</li>
<li>- Item 6</li>
<li>- Item 7</li>
<li>- Item 8</li>
</ul>

CSS

ul {
column-count: 3;
max-width: 40rem;
}

显示方式

enter image description here

但是,所有列的宽度都相等,这会导致它们之间的间距不同。我如何调整 css 列以获得类似这样的内容,其中每列的宽度取决于内容?

我想要实现的目标:

enter image description here

谢谢!

编辑: 我应该提到我需要使用 CSS 列,因为这些元素列表是通过 CMS 动态生成的,所以如果可能的话,我想找到一个纯 CSS 解决方案以避免必须引入 Javascript 来操作 DOM。谢谢。

最佳答案

仅供引用,因为目前它只是实验性的:

this can be tested in few browsers,

see also http://caniuse.com/#search=grid

A tutorial among others https://css-tricks.com/snippets/css/complete-guide-grid/

所以 display:grid 总有一天会有所帮助:但是,布局仍然是逐行喷涂

ul {
padding: 1em ;
margin: 2em;
border: solid 1px;
list-style-type: none;
display: grid;
grid-template-columns: auto auto 1fr;
grid-gap: 0 2em;
}
<ul>
<li>- Item 1 - this is the item's name here.</li>
<li>- Item 2</li>
<li>- Item 3</li>
<li>- Item 4</li>
<li>- Item 5</li>
<li>- Item 6</li>
<li>- Item 7</li>
<li>- Item 8</li>
</ul>


如果您在服务器端使用例程或 javascript 来计算您的元素,那么您可以强制按列喷洒它们:(通过 js/jQuery 的示例:http://codepen.io/gc-nomade/pen/BpZZQW播放和添加/删除 lis )

ul {
padding: 1em 1em 1em 4em;
margin: 2em;
border: solid 1px;
list-style-type: none;
display: grid;
grid-gap: 0 2em;
padding:1em ;
grid-template-columns: 0 auto auto 1fr;/* last one set to use all room left */
grid-auto-flow: column;
}

/* span a first-element throgh all rows , to be injected and updated from server side or via javascript on the fly */
ul:before {
content: '';
grid-column: 1;
/* short hand : grid-row:1/4;*/
grid-row-start: 1;
grid-row-end: 4;/* value to updated to match row numbers + 1 */
}
<ul>
<li>- Item 1 - this is the item's name here.</li>
<li>- Item 2</li>
<li>- Item 3</li>
<li>- Item 4</li>
<li>- Item 5</li>
<li>- Item 6</li>
<li>- Item 7</li>
<li>- Item 8</li>
</ul>

关于css - 如何使用 css 列将列宽调整为内容大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41813456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com