Tuesday 31 March 2015

Insert image using only CSS

Problem:

How can I insert an image using only CSS?

Solution:

While there are many ways to do this, we will discuss one below.

Assuming the following html:


This is an image of an icon <span class="myicon"></span>

We can make the span display an icon using the following CSS for the class "myicon", with the stuff in bold being stuff you'll want to replace:


.myicon {
    display: inline-block; /* or 'block' if not inline */
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: url("path/to/your/image") no-repeat;
    background-size: 85pt 8.5pt; /* (optional) resize image */
    width: 85pt; /* Width of image */
    height: 8.5pt; /* Height of image */
    padding-left: 85pt; /* Equal to width of new image*/

    margin-left: 2pt; /* optional */
    margin-right: 2pt; /* optional */
}

Notes:

While the situation is not common, there can be cases where designers might only have access to the CSS and not the HTML, with the developer applying the desired class to the span or div for the designer. If yours is one of these situations then this trick can come in handy.

Note that you can also use this trick to add other content by using the 'content' attribute. While this is out of the scope of this post, you can feel free to experiment and see how it goes.

Also note that this trick will only work with CSS3 and beyond (because of the 'box-sizing' attribute).

References:

No comments:

Post a Comment