2009-02-13 141 views
22

我试图在<th>元素中放置链接,并让<a>元素填充<th>的整个空间。虽然我可以用100%的宽度水平填充它,但是垂直填充会证明是麻烦的。身高:100%似乎没有效果。CSS:使块元素填充父元素的整个空间?

我想这样做,以便用户可以单击单元格中的任意位置以激活链接。我知道我可以把onClick属性放在<th>本身上,并通过javascript处理它,但我想这样做的“正确”的CSS方式。

澄清:表的每一行可以有不同的高度,因为内容是动态的,所以使用固定高度的<a><th>元素的解决方案将无法正常工作。

下面是一些示例代码:

<style type="text/css"> 
th { 
    font-size: 50%; 
    width: 20em; 
    line-height: 100%; 
} 
th a { 
    display:block; 
    width:100%; 
    height:100%; 
    background-color: #aaa; 
} 
th a:hover { 
    background-color: #333 
} 
</style> 
<table border=1> 
    <tr> 
    <th><a href="foo">Link 1</a></th> 
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dapibus tortor.</td> 
    </tr> 
    <tr> 
    <th><a href="foo">Link 2</a></th> 
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dapibus tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dapibus tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam dapibus tortor. </td> 
    </tr> 
</table> 

And here is a page with that exact same code

正如你可以看到,如果你将鼠标放置链接时,<a>元素不是垂直填充产生一个尴尬的样子。我可以通过将悬停背景置于“th:悬停”样式来修复悬停背景,但如果您单击实际的a标签所在的位置,链接仍然只能实际发挥作用。

回答

10

只是改变级风格这个

th { 
    font-size: 50%; 
    width: 20em; 
    height: 100%; 
    line-height: 100%; 
} 

欢呼

+0

只需增加100%的高度;) – gonxalo 2009-02-13 18:07:58

0

你需要给<th>的高度,让你的风格块最终会像

th { 
    font-size: 50%; 
    width: 20em; 
    height: 8ex; 
    line-height: 100%; 
} 

编辑:实际上,对于高度你应该使用像“前”一纵措施,而不是一个“em”的水平尺度。示例已更改以反映该情况。

+0

问题是表格中每一行的高度需要是动态的。即使你设置了高度,内容也会根据浏览器的宽度来调整大小,所以你不能依赖它是一个确切的高度。 – OverloadUT 2009-02-13 18:02:53

0

为了做到这一点,你可以设置你的“a”元素的高度像素,而不是百分比。

如果指定百分比,100%将最终成为TEXT本身的高度。

像素高度会给你一个静态高度,并将适用于这种情况。

td a {height: 100px;} 
+0

不幸的是,每个表格行的高度会根据内容而有所不同,我不希望每行都处于固定高度。 – OverloadUT 2009-02-13 18:04:54

3

由于@Hober说,你需要给<th>一个高度。你也可以在那里使用height: 100%

如果你知道你的尺寸<th>,它看起来像你可能不会在这种情况下(因为他们在旁边),我有幸添加了一个填充来推动<a>出去边缘(通过<th>本身的任何填充),然后将其带回相应的负边距。就像这样:

th a{ 
    padding: 10px 0; 
    margin: -10px 0; 
} 
+0

为我工作,谢谢! – flash 2009-12-10 21:04:25

0

你可以使用JavaScript这样做(见下文)。

<style type="text/css"> 
th { 
font-size: 50%; 
width: 20em; 
background-color: #aaa; 

} 
.off { 
background-color: #aaa; 
} 
.on { 
background-color: #333 
} 


<th onmouseover="this.className='on'" onmouseout="this.className='off'">><a href="foo">Link 1</a></th> 
0

th元素需要为其指定高度。给它100%的高度应该使元件扩展到其容器的高度(即行的高度)。这可能无法在IE 6中正常工作,您可以尝试添加_height: 1%来解决IE6问题 - 我没有IE6来测试它,但是我在Firefox中测试过,它似乎正在做你想做的。

th { 
    height: 100%; 
} 
0

我得到这个最接近...

th { 
    float: left; 
    overflow: hidden; 
    font-size: 50%; 
    width: 20em; 
    margin: auto; 
} 
th a { 
    display: table; /* or block, up to you */ 
    margin: none; 
    width:100%; 
    height: 1px; 
    background-color: #aaa; 
    padding: 20%; 
} 

但它使所有的行相同的高度。也许别人可以解决,如果这是一个问题。