13

A div has a tilable background. The height of this div will depend on its content. I need the div to stretch by a multiple of the background image's size.

For instance, the background is a 64x64 image. So, if the div's height is to increase, I want to do so by steps of 64px.

Is this possible with CSS? I've not found leads using google. Thanks for your time!

Jem
  • 6,226
  • 14
  • 56
  • 74
  • 3
    You can't do this in css - in general, css doesn't let you set styles conditional upon the content of a dynamically sized element. – Oliver Feb 10 '12 at 14:01
  • 1
    In simple css it can't be achieve. Try jQuery for that. – NewUser Feb 10 '12 at 14:14
  • @newuser - You don't need jQuery to do this and plain javascript will do the same thing. – Rob Feb 10 '12 at 15:47

3 Answers3

6

To my knowledge this cannot be done in CSS, but you could probably solve it with some javascript. If you have access to jQuery:

$(function() {
    $div = $('#the_div_id');
    var remainder = $div.height() % 64;
    var newHeight = $div.height() + (64-remainder);
    $div.css('height', newHeight);
});
Christoffer
  • 2,125
  • 15
  • 21
  • Yep, I think I'll go down that way, after the document gets ready. thanks =) – Jem Feb 10 '12 at 14:38
  • You're welcome. By the way, `$(function() { ... });` is shorthand for "do this when the DOM is ready", in case you are new to jQuery. And as @Rob said, it can be done in native Javascript as well, I just personally prefer jQuery. – Christoffer Feb 10 '12 at 15:09
  • I used your answer in a similar way that just tip toes around heights a little differently: $pageContent = $('#pageContent'); var remainder = $div.height() % 64; remainder = 64 -remainder; $div.css('padding-bottom', remainder); if you're trying to use heights other places in your css that you don't want to modify, this will grow the div to a proper height – willcwf Oct 28 '14 at 17:36
6

One solution (depending on your specific case) could be to use the new background-size CSS property. I've left the declarations separate for clarity:

div.yourDiv {
    background-image: url('yourImage.jpg');
    background-repeat: repeat;
    background-size: contain;
}

Then, whatever the size of you div, your image will tile perfectly without being cut off. Older browsers will just get the tiled image, which may or may not be an issue.

CherryFlavourPez
  • 7,529
  • 5
  • 45
  • 47
0

What is the content of the div? It sounds like rather than setting the size of the div to the correct value, you need to pay attention to the content - this post details some pretty simple techniques to implement vertical rhythm, which should work (ie. by using a line height of 64px)

Jordan Wallwork
  • 3,116
  • 2
  • 24
  • 49
  • It's actually about a kitsch ui: The div represents a ladder, and its height is proportional to the div's height from the top of the screen - makes tiling necessary as to connect to the terminator elements. – Jem Feb 10 '12 at 14:37