user2524653
user2524653

Reputation: 108

div as Circle Showing percentage at the Middle javascript

I Have a div as a circle, with the inner text showing values as percentage say(20%). The problem is the inner text is not displaying exactly at the center of the circle.

The inner text is a dynamic value based on some results in percentage. The radius of the circle is based on the percentage values returned as result.The percentage values returned should be displayed exactly at the center of the circle. Could Someone help me with this.

Thanks.

Heres the code,

<style>
    #circle {
        border: 1px solid red;
        border-radius: 50%;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        background:blue;
    }
</style>

<div id="circle"></div>  

<script>
    $(function(){
        var maxWidth = 500, // This is the max width of your circle
        percent = Number($('#result').text()); // This is the percentage value
        percent = percent / 100;

        $("#circle").css({
            "width" : maxWidth * percent,
            "height" : maxWidth * percent,
        });
        circle.innerText =$('#result').text() + "%";
</script>

Upvotes: 1

Views: 587

Answers (2)

Pallab
Pallab

Reputation: 285

This work out for me.

display: table-cell;
vertical-align: middle;

You can check the fiddle:

http://jsfiddle.net/Pallab/zCfyV/embedded/result/

Upvotes: 0

Butt4cak3
Butt4cak3

Reputation: 2429

You can add another DIV inside the circle which holds the text and add position: relative to #circle in the CSS. Also add this:

#circle>* {
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translateX(-50%) translateY(-50%);
    -moz-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}

position: absolute and top: 50% / left: 50% will place the top-left corner of the inner DIV in the middle of the circle. The transform shifts it 50% of its own size to the left/top.

Upvotes: 1

Related Questions