How to display text on image using css

Css position can be used to place a text over an image. This can used to place some text like alpha or beta over a logo. Or if you want to create multiple logo for different countries, you can place country name as text on the image. Here are few approaches to achieve this using css.

Text in div with absolute position

Here is the code and the rendered outcome:

<div style="position:relative">
<img src="http://infoheap.com/img/demo_logo_infoheap_80.png" />
<div style="position:absolute; left:300px;top:0px;color:#888;font-size:10px;">alpha</div>
</div>
refresh

Few things to note:

  1. position:absolute renders the object relative to its containing block (nearest ancestor whose position is not static)
  2. position:absolute boxes are taken out of the normal flow (For detailed info see CSS 2.1 specification)

Text in div with relative position css

Here is the code and the rendered outcome:

<div style="line-height:25px;">
<img src="http://infoheap.com/img/demo_logo_infoheap_80.png" />
<div style="position:relative; left:300px;top:-90px;color:#888;font-size:10px;">alpha</div>
</div>
refresh

Few things to note:

  1. position:relative renders the object relative to its position in normal flow. Please note the negative value of property top.
  2. Since we don’t need a positioned parent, There is no need of having position:relative in the containing div.

Text in div with background image css

Here is the code and the rendered outcome:

<div style="background:url(http://infoheap.com/img/demo_logo_infoheap_80.png) no-repeat;background-size:371px 80px;height:80px;width:371px">
<div style="position:relative; left:300px;top:0px;color:#888;font-size:10px;">alpha</div>
</div>
refresh

Few things to note:

  1. Here since image is container div’s background it does not come in normal flow.
  2. We had to give container div a width and height so that it is of the size of the img
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments