Friday, March 20, 2015

How to place text inside a circle using css

We often require some text to be placed inside a circle. I am gonna show you how to do it in very simple steps.



STEP 1: Create a div holder

Create a div with fixed width and height and give it some border so that we can recognize its presence. Lets say
<div style="width:100px;height:100px;border:1px solid gray;">  </div>
This is our holder

STEP 2: Create a circle with CSS

Create another div inside earlier one with fixed width and height ( width should be equal to height) and with border-radius
i.e width==height==border-radius
<div style="width:100px;height:100px;border-radius:100px;background-color:red;"></div>
The result is gonna be like this


STEP 3: Create another div to place the text inside it

Now create another div to hold the text and that should be at the level as we created in step 2.
<div style="width:100%;text-align:center;"></div>
STEP 4: Adding the trick

Set position attribute as relative to the parent
Set position attribute as absolute to the div which has text.
Set top attribute as 40% to the div which has text
<div style="height:100px;width:100px;border:1px solid gray;position:relative;margin:240px;">
    <div style="height:100px;width:100px;background-color:red;border-radius:100px;">
    </div>
    <div style="position:absolute;top:40%;text-align:center;width:100%;">
        Sam
    </div>
</div>

Result:

Fiddle available http://jsfiddle.net/mannemvamsi/jbt3y78d/1/

No comments:

Post a Comment