简体   繁体   中英

How to center a text inside a div using javascript

I have a javascript code that generates html to build a bar with css, but I need to center a text in the middle of the bar, this is my code:

                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")
                }

I would like the text "50%" in the "disk" column to be centered on the bar graph

忙碌的猫

Can someone help me? It seems something elementary of css but I do not give with the error.

Very easy with 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> 

Ready.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM