请参阅下面由 HTML 和 CSS 生成的表格。你可以在这里看到它的截图:https://www.dropbox.com/s/i7yszk2v7jlwdxr/Screenshot%202013-12-17%2012.58.00.png
我的问题是如何确保该表格只占据它需要的水平空间——而不是页面的整个宽度?这似乎是一个非常简单的问题:只需删除“width: 100%;”即可。在第 5 行。然而,如果你看到它以一种没有人真正想要的方式搞砸了 table :https://www.dropbox.com/s/hztj01y3901whv9/Screenshot%202013-12-17%2013.01.18.png
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.myStyle table { border-collapse: collapse; text-align: left; width: 100%; }
.myStyle {font: normal 12px/150% Arial, Helvetica, sans-serif; background: #fff; overflow: hidden; border: 1px solid #801D99; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; }
.myStyle table td,
.myStyle table th { padding: 3px 10px; }
.myStyle table thead th {background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #801D99), color-stop(1, #801D99) );background:-moz-linear-gradient( center top, #801D99 5%, #801D99 100% );filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#801D99', endColorstr='#801D99');background-color:#801D99; color:#FFFFFF; font-size: 15px; font-weight: bold; border-left: 1px solid #801D99; }
.myStyle table thead th:first-child { border: none; }
.myStyle table tbody td { color: #801D99; font-size: 12px;border-bottom: 1px solid #995993;font-weight: normal; }
.myStyle table tbody td:first-child { border-left: none; }
.myStyle table tbody tr:last-child td { border-bottom: none; }
</style>
</head>
<body>
<div class="myStyle">
<table>
<thead>
<tr>
<th colspan="2">My table.</th>
</tr>
</thead>
<tbody>
<tr><td>1.</td><td>B</td></tr>
<tr><td>2.</td><td>C</td></tr>
<tr><td>3.</td><td>D</td></tr>
</tbody>
</table>
</body>
</html>
最佳答案
将div.myStyle
元素的display
修改为inline-block
;这可以防止 table
占用父级宽度的 100%
(因为 width
以百分比分配父级的 width
必须明确说明/定义),因此只占用它需要的空间,并且父 div
元素会根据其内容的大小折叠。 Demo .
或者,您可以忽略 display
属性,而是设置:float: left;
这将实现相同的效果(demo),但请注意当元素为 float
时,其他相邻的兄弟元素占据右侧的空间。
关于html - CSS Styles 如何让这个表格不填满整个页面宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641473/