如何使用JavaScript在div内居中放置文本

时间:2019-01-16 14:09:09

标签: javascript css arrays

我有一个javascript代码,该代码会生成html以使用css构建栏,但是我需要将文本居中放置在栏中间,这是我的代码:

                render: function(data, type, row, meta){
                    coord_str = data;
                    return $("<div></div>", {
                        "class": "bar-chart-bar"
                    }).append(function(){
                        var bars = [];
            color = 'blue';                         
                        }                           
                            bars.push($("<div></div>",{
                                "class": "bar " + "bar1"
                            }).css({
                                "background-color": color,
                                "width": coord_str + "%"
                            }))
                        return bars;
                    },"50%").prop("outerHTML")
                }

我希望“磁盘”列中的文本“ 50%”以条形图为中心

a busy cat

有人可以帮助我吗?似乎是CSS的基本知识,但我没有给出错误。

2 个答案:

答案 0 :(得分:2)

使用Flexbox非常容易:

div {
  position: relative;
  width: 200px;
  height : 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  border : green solid 2px;
}

div:before{
  content: "";
  background: lightblue;
  position: absolute;
  top: 0;
  left: 0;
  width : 60%;
  height: 100%;
}

span{
   z-index : 1;
}
<div>
  <span>Centered text!</span>
</div>

答案 1 :(得分:0)

准备好了。

.bar-text {
    z-index-1; 
    position: absolute;  
    width: 100%; 
    text-align: center; 
    margin-top: -2px;
}