views:

44

answers:

2
+1  Q: 

css width interval

Ok, here's a problem I've never run into before. I would like to use CSS to specify that an elements width should always be in 10 pixel intervals. So, for example, if the width of an element is 11, it would get bumped up to 20, 56 => 60, 138 => 140, etc...

I doubt CSS has a way to do this but thought I'd ask anyway. Something like this would be nice:

div { width-interval: 10px; }
+1  A: 

The problem with this is that block-level elements are always the size of the window unless you specify otherwise. Once you specify a more specific width, you don't need a width inverval.

The two cases this would be different are;

  1. If the block level element is shrink wrapped (in the case of floats and inline-blocks)

  2. If the element has a relative width, ie a percentage.

But if you are setting it to be relative, you wouldn't need intervals, because it's supposed to be relative to other things on the page, so that would get complicated when other things had to be adjusted to compensate. For instance, if I had two divs:

<div id="one"></div>
<div id="two"></div>

and a rule:

#one {
width: 50%;
width-interval: 25px;
}

#two {
width: 50%;
width-interval: 27px;
}

Which one wins? If it's important for lining up pictures or text, you probably don't want either to trump the other, but it can't ignore both.

I think the idea is good, but would probably be better handled by javascript, since you are requiring it to be both dynamic and based on the "nearest" interval. This could work:

$(function () {

$(div).each(function() {
    var cur_width = $(this).width();
    var inverval_diff = cur_width % 10;
    $(this).width(cur_width + inverval_diff);
});

});

The above is in jquery, in case you don't use that as your js framework.

Anthony
A: 

css doesn't have such property, but you are able to style width of elements with additional JavaScript such as:

<script type="text/javascript">
$(function(){
    var widthInterval = 20;
    $('div').each(function(){
        var $this = $(this);
        var divisions = parseInt($this.width() / widthInterval) + 1;
        var resWidth = (divisions * widthInterval) + "px";
        $this.css('width', resWidth);
        console.log("Resulted width: " + resWidth);
    });
});    
</script>

Hope it helps.

Juraj Blahunka
The correct answer to the question is that this is impossible without javascript at the moment, so I'm accepting this answer.
spudly