tyebillion tyebillion - 3 months ago 8
Javascript Question

How to horizontally centre a stars rating image within a Bootstrap column?

I have a stars rating image which is controlled using Javascript and CSS to display a rating out of five (in quarter steps, twenty is the dimensions of the star in pixels):

stars.png

$.fn.stars = function() {
return $(this).each(function() {
var val = Math.round(parseFloat($(this).html())*4)/4;
var size = Math.max(0, (Math.min(5, val)))*20;
var $span = $("<span />").width(size);
$(this).html($span);
});
}

$(function() {
$("#avg-rating").html('<span class="stars">{{ avg_rating }}</span>');
});

span.stars, span.stars span {
display: block;
background: url(stars.png) 0 -20px repeat-x;
width: 100px;
height: 20px;
}
span.stars span {
background-position: 0 0;
}


The image is displayed in a Bootstrap column:

<div class="container-fluid">
<div class="text-center">
<div class="row">
<div class="col-xs-6"><div id="avg-rating"></div></div>
<div class="col-xs-6">blah blah</div>
</div>
</div>
</div>


The image is currently left justified in its column. I have tried several things in CSS to align the image horizontally in its column, such as adjusting the display attribute or background position. But I am unable to move the image without upsetting the functionality of the image manipulation.

Update

Using inline-block instead of block messes up the placement of the stars (image should show four lighted stars out of five):

span.stars, span.stars span {
display: inline-block;
...


stars mess

Answer

Your problem seems to stem from here:

span.stars, span.stars span {
    display: block;
    background: url(stars.png) 0 -20px repeat-x;
    width: 100px;
    height: 20px;
}

You've set the star container to 'display: block' which makes it take up the whole line. You want it to be an inline-block with a width smaller than the full-width available so that it can be centred.

Comments