Setting width of table cell contents based on available width
I have an HTML table whose cells contain, among other things, spans, like this:
...
<td>
<span style="height: 20px; width: 20px; margin-left: 2px;">
<span style="height: 20px; width: 20px; margin-left: 2px;">
<span style="height: 20px; width: 20px; margin-left: 2px;">
</td>
...
I'm looking for a way to shrink the width of those spans, rather than line wrap them, when the containing table cell is too narrow to show them all on one line. I tried playing around with setting the spans' max-width
to 20px
and then using a percent for the width, but that does no开发者_如何学Pythont work because the table cell tries to be only as wide as its contents.
The minimum table cell width would be the width needed to display the header on 1 line.
For the visual types, here's what I currently have when there is enough width:
Here's what I currently have when there is not enough width:
And here's what I would like it to look like when there is not enough width for each span to be a full 20px:
In case it's not obvious, the spans are the colored squares in the TXEs
, RDBs
, and RavenNets
columns.
Use <td nowrap>
or <td style="white-space:nowrap;">
to avoid the wrapping. A table cell should generally expand to fit its contents, unless it is allowed to wrap, or you have constrained its width in some other way.
Have you considered setting a min-width on the td? or a wrapper div inside the td, but outside the spans?
This sorta kinda seems to do something close to what you want in Firefox 3.6. The crucial requirement seems to be that the table's width cannot be in pixels.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="http://yui.yahooapis.com/3.0.0/build/cssreset/reset-min.css">
<style type="text/css">
.indicator {
display:block;
white-space:nowrap;
min-width:8px;
max-width:300px;
width:100%;
}
.indicator li {
border:outset 2px;
display:inline-block;
height:80px;
min-width:2px;
max-width:80px;
padding:0 0 0 2px;
width:25%;
}
.ok { background:#0f0 } .caution { background:#ff0 }
.alert { background:#f00 } .inactive { background:#0ff }
table { width:100% }
td { width:100% }
</style>
</head>
<body>
<table><tr><td>
<ul class="indicator">
<li class="ok"></li> <li class="caution"></li>
<li class="alert"></li> <li class="inactive"></li>
</ul>
</td></tr></table>
</body>
</html>
I couldn't find a satisfactory pure-CSS way to do what I wanted. I already had an application config file implemented (like a .ini
file, more or less) so I just added my desired width to this config. It's not a general-purpose solution but it fits my requirements just fine.
精彩评论