Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

html - CSS: Make a block element fill the entire space of a parent element?

I am trying to put a link in a <th> element and have the <a> element fill the entire space of the <th>. While I can get it to fille horizontally with width:100%, getting it to fill vertically is proving to be troublesome. height:100% seems to have no effect.

I want to do this so that the user can click anywhere in the cell to activate the link. I know I could put an onClick property on the <th> itself and handle it via javascript, but I would like to do it the "proper" css way.

Clarification: Each row of the table can have a different height because the content is dynamic, so solutions that use a fixed height for the <a> or <th> elements will not work.

Here is some sample code:

<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

As you can see if you mouseover the link, the <a> element is not filling vertically which produces an awkward look. I could fix the hover background by putting it in a "th:hover a" style, but the link would still only actually function if you clicked where the actual a tag is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

just change th style to this

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

cheers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...