gpt4 book ai didi

html - "Standard"减少表列宽度以适应子元素的方法

转载 作者:太空狗 更新时间:2023-10-29 15:11:16 25 4
gpt4 key购买 nike

我有一个已知宽度、776 像素和三列的表格。第三列的宽度已知,216 像素,但其他两列的宽度未知。我想要的行为是第二​​列与其子元素具有相同的宽度。无论剩下多少宽度,776 - 216 - 2nd 都将是第一列的宽度。

我找到了一个示例,该示例将列的宽度设置为应将其宽度最小化为 1 个像素。这似乎确实有效,但它似乎是一个 hack,我不明白为什么它有效。是否有更“标准”的方法来达到相同的结果?

这是我的带有内联 CSS 的 HTML 示例:

<table style="width:776px; height:48px;">
<tr>
<td style="height:48px;">
<!-- Note: Setting font size to zero prevents white space from contributing to an inline block element's width -->
<div style="background:#f0f0f0; border:solid 2px #808080; font-size:0; margin-left:8px; text-align:center;">
<a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Art</h3></a>
<a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Events</h3></a>
<a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Papers</h3></a>
<a href="#"><h3 style="display:inline-block; font-size:20px; line-height:28px; padding:8px;">Research</h3></a>
</div>
</td>
<!-- Note: Setting width to one pixel removes horizontal spacing -->
<td style="vertical-align:middle; width:1px; height:48px;">
<h3 style="margin-left:8px;"><label for="search">Search:</label></h3>
</td>
<td style="vertical-align:middle; width:216px; height:48px;">
<input id="search" style="margin-left:8px; width:208px;" type="text" value="" maxlength="32">
</td>
</tr>
</table>

最佳答案

嗯,一个简单的方法是将第一个单元格设置为 width: 100%。这将迫使它尽可能多地填充父表的宽度。然后,在第三个单元格中放置一个 216px 内容元素(如 div)。

表格的单元格始终尽量尊重其内容。所以这样,第二个 div 会在中间被挤压,只是尊重它自己的内容。第 3 个将尊重其 216px 内容,第 1 个将填充其余内容。

Working JsFiddleExample

<table>
<tr>
<td>1stContent</td> <!-- Fills what it can -->
<td>2ndContent</td> <!-- Squized in the middle -->
<td>
<!-- Will respect the width of its content -->
<div class="dv3rd">
216px
</div>
</td>
</tr>
</table>

CSS:

table {
width: 776px;
background: silver;
}

td:nth-child(1) {
width: 100%;
background: red;
}

td:nth-child(2) {
background: green;
}

td:nth-child(3) {
background: blue;
}

.dv3rd {
width: 216px;
}

但是

如评论所述,您不应该将表格用于页面布局。一个简单的替代方法是使用 css 表格,您的 div 可以像 display: tabledisplay: table-cell 元素一样工作。

这是相同的示例,但使用的是 div:

Working JsFiddleExample - Tableless

<div class="table">
<div>
1stContent
</div>
<div>
2ndContent
</div>
<div>
<div class="dv3rd">
216px
</div>
</div>
</div>

CSS:

.table {
width: 776px;
background: silver;
display: table;
}

.table > div:nth-child(1) {
display: table-cell;
width: 100%;
background: red;
}

.table > div:nth-child(2) {
display: table-cell;
background: green;
}

.table > div:nth-child(3) {
display: table-cell;
background: blue;
}

.dv3rd {
width: 216px;
}

关于html - "Standard"减少表列宽度以适应子元素的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25895293/

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