我有一个星级评级图像,它使用 Javascript 和 CSS 控制以显示五分之一的评级(以四分之一为单位,二十是星星的尺寸,以像素为单位):
$.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;
}
图像显示在 Bootstrap 列中:
<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>
图像当前在其列中左对齐。我在 CSS 中尝试了几种方法来在其列中水平对齐图像,例如调整显示属性或背景位置。但是我无法在不破坏图像处理功能的情况下移动图像。
更新
使用 inline-block 而不是 block 会弄乱星星的位置(图片应该显示五颗中有四颗亮着的星星):
span.stars, span.stars span {
display: inline-block;
...
最佳答案
你的问题似乎源于这里:
span.stars, span.stars span {
display: block;
background: url(stars.png) 0 -20px repeat-x;
width: 100px;
height: 20px;
}
您已将星形容器设置为“display: block”,使其占据整行。您希望它是一个宽度小于可用全宽的行内 block ,以便它可以居中。
这是一个如何工作的例子: https://jsfiddle.net/f6L8gr1b/2/
关于javascript - 如何在 Bootstrap 列中将星级评分图像水平居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275021/