How to center text in div or table cell, have a link apply to entire cell/div, where text may be 1/2/3 lines
I'm trying to create buttons from either divs or table cells (or some combination) where the text can be variable length (and thus print out using 1, 2, or 3 lines) but the link should both turn the entire cell a different cell on hover and the link should apply to the entire cell.
开发者_StackOverflowI can either get the text center aligned but the link/background only applied to the text or I can get the entire cell linked, but the text floats to the top.
Here's my HTML/PHP:
<div id="rollover"><div class="container">
<table><tr>
<?php foreach ($field_landing_button_links as $btnlink) : ?>
<td class="list" width="<?php echo $width;?>%">
<a href ="<?php echo $btnlink['display_url'];?>">
<div class="cell"><?php echo $btnlink['display_title'];?></div>
</a>
</td>
<?php endforeach; ?>
</tr></table>
</div></div>
And my Styles:
#rollover div.container {width: 549px;} #rollover div.container td {text-align: center; vertical-align: middle;} #rollover div.container tr{ height: 48px; background-image: url("../../images/div_bg.jpg")} #rollover div.container td a { cursor: pointer; display:block; color: #FFF; margin: 0; width: 100%;} #rollover div.container td a:hover {background-color: red; }
The above properly vertically aligns the text, but the link/background color only apply to the text. I'd like something that works in at least IE7/8, FF 2/3, Chrome, and Safari.
Thanks in advanced!
D
You can set the line-height
of the <a>
to the full height of the row to get the text to vertically align:
#rollover div.container td a { height: 48px; line-height: 48px; }
Note that this only works if the row is a fixed height (which it appears to be). Otherwise, I think you'd be out of luck and have to use the hover
and click
events of the td itself.
There's a number of ways to handle this. The easiest way would be with javascript. Specifically jQuery. Doing that, you could rid yourself of the table altogether. Set your A tags as block, give them a width, float them, then on page load, iterate through them to find the tallest one, then iterate through them a second time adding the necessary top and bottom padding to get them all to look the same height visually.
If you don't have to make it work with IE, you can get by with just using CSS and the 'display table/table-cell' properties to then enable vertical-align:middle.
I've used a combination of those in the past, using the CSS for good browsers and falling back to the JS solution for IE.
精彩评论