Chris Coyier, of CSS-Tricks, tweeted the other day asking for questions for an upcoming article he’s writing for Smashing Magazine. I’m currently working on a website for a design course that I’m taking and had a couple questions regarding background-images. I produced a table using PHP and wanted the current date to be highlighted using a background-image in CSS. I had some issues and e-mailed Chris. He promptly responded with the following information. Enjoy!
Hey William,
This is really a rock-and-a-hard-place scenario. CSS background-images are not resizeable, so that’s out. The other way to include an image on the page is an inline . There are resizeable, so we may be onto something. The go-to method for stretching an image to the size of it’s parent is to use absolute positioning and set the top, bottom, left, and right values to zero. Unfortunately, the parent needs to have relative positioning for this to work, and table cells to not accept relative positioning.
Divs, however, do accept relative positioning. So a div inside will stretch to the width of the parent table cell, but not the necessarily the height, and we are unable to force it because of the no-relative-positioning-on-table-cells problem from above.
With CSS alone, we can almost get it:
<td class="currentDay">
<div>
<img src="images/circle.png" class="circle" alt="" />
19
</div>
</td>
td { padding: 5px; vertical-align: middle; text-align: center; }
td div { position: relative; }
.circle { position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
The height is still a problem though, and I’m not seeing a pure CSS solution. What we need to do is set the height and width of that image to be the exact height and width of the table cell that it’s in. We can lean on a bit of jQuery to do that math for us:
$(function() {
var theImage = $(".circle");
var theCell = theImage.parent().parent();
var theWidth = parseInt(theCell.css("width")) + parseInt(theCell.css("padding-left")) + parseInt(theCell.css("padding-right"));
var theHeight = parseInt(theCell.css("height")) + parseInt(theCell.css("padding-top")) + parseInt(theCell.css("padding-bottom"));
$(".circle")
.width(theWidth)
.height(theHeight)
.css({
"top": -parseInt(theCell.css("padding-top")),
"left": -parseInt(theCell.css("padding-left"))
});
});
Kind of a lot of work for such a seeminly simple problem, but at least it works and it’s adaptable.
http://css-tricks.com/examples/ImageToCellSize/
-Chris
I hope this helps some people. Thanks again Chris!!












