我有一个.yellow-element
样式的三个div width: auto
,位于一个宽度也为auto
的表列中。这导致表的宽度和最宽的div 一样大,而则使每个div都变得最宽,即使这不是按内容的必要:
#info-table td {
padding: 10px;
border: 1px solid #ddd;
}
.info-table-1 {
width: 100px;
}
.info-table-2 {
width: auto;
}
.yellow-element {
font-size: 100%;
font-weight: bold;
color: var(--body-font-color);
background-color: yellow;
border: 1px solid black;
border-radius: 25px;
padding: 5px;
margin-right: 20px;
width: auto;
height: 30px;
margin-bottom: 15px;
}
<table id="info-table">
<tr>
<td class='info-table-1'>Total Something:</td>
<td class='info-table-2'>
100500/100500
</td>
</tr>
<tr><td class='info-table-1'>Yellow Elements:</td>
<td class='info-table-2'>
<div class='yellow-element' title='title1'>long long long long long long long long long long long long long text</div>
<div class='yellow-element' title='title2'>average average average text </div>
<div class='yellow-element' title='title3'>small text</div>
</td></tr>
</table>
我见过的答案建议将display: inline-block
放在类.yellow-element
上,但是虽然它确实起作用,但单独固定每个div的宽度,却将所有div放在同一行上,即不是我想要的。
答案 0 :(得分:2)
您可以将.info-table-2
放入flex容器。然后,您可以更轻松地控制yellow-element
单元的布局。
#info-table td {
padding: 10px;
border: 1px solid #ddd;
}
.info-table-1 {
width: 100px;
}
.info-table-2 {
/* width: auto; */ /* <-- removed */
display: flex; /* <-- added */
flex-direction: column; /* <-- added */
align-items: flex-start; /* <-- added */
}
.yellow-element {
font-size: 100%;
font-weight: bold;
color: var(--body-font-color);
background-color: yellow;
border: 1px solid black;
border-radius: 25px;
padding: 5px;
margin-right: 20px;
width: auto;
height: 30px;
margin-bottom: 15px;
}
<table id="info-table">
<tr>
<td class='info-table-1'>Total Something:</td>
<td class='info-table-2'>
100500/100500
</td>
</tr>
<tr>
<td class='info-table-1'>Yellow Elements:</td>
<td class='info-table-2'>
<div class='yellow-element' title='title1'>long long long long long long long long long long long long long text</div>
<div class='yellow-element' title='title2'>average average average text </div>
<div class='yellow-element' title='title3'>small text</div>
</td>
</tr>
</table>
答案 1 :(得分:1)
使用以下内容:
.yellow-element {
clear:both;
float:left;
}