Backo
Backo

Reputation: 18871

Improving HTML and CSS on using background images

Is there a better way to have the same output generated by the following code?

The HTML code is:

<div class="imaged backgrounded"></div>
<div class="title">
  Title test text
</div>

The CSS code is:

.imaged {
    background: transparent url("/images/sprites.png") no-repeat;
    float: left;
    height: 24px;
    margin: 0 8px 0 0;
    width: 24px;
}

.backgrounded {
    background-position: -16px -106px;
}

.title {
    display: inline-block;
    margin-top: 2px;
}

Upvotes: 1

Views: 164

Answers (3)

thirtydot
thirtydot

Reputation: 228192

What you have looks fine.

Here are some trivial improvements:

  • The default background-color is transparent, so you don't need to specify it.
  • You don't need quotes around that image url.
  • I would put the width and height properties next to each other, because they are related.
  • display: inline-block doesn't work on elements that aren't naturally inline in IE7, a browser that still unfortunately has some market share. If your site has any IE7 users, you should fix it.

So, this is the final result:

.imaged {
    background: url(/images/sprites.png) no-repeat;
    float: left;
    width: 24px;
    height: 24px;
    margin: 0 8px 0 0;
}
.backgrounded {
    background-position: -16px -106px;
}
.title {
    margin-top: 2px;
    display: inline-block;
    *display: inline;
    zoom: 1;
}

You should also consider changing <div class="title"> to something more semantic, such as h2 or h3 depending on how important the titles are.

Yes, this is all very pedantic.

Upvotes: 2

Magnum26
Magnum26

Reputation: 275

I agree with Will, I always put my background positions on a new line.

.imaged {
background: transparent url("/images/sprites.png") no-repeat;
background-position: -16px -106px;
float: left;
height: 24px;
margin: 0 8px 0 0;
width: 24px;
}

But you can also do it the shortened way

background: transparent url("/images/sprites.png") no-repeat -16px -106px;

Upvotes: 0

Mr.T.K
Mr.T.K

Reputation: 2356

You never create separate class for background position. you can also do like below

.imaged {
    background: transparent url("/images/sprites.png") -16px -106px no-repeat;
    float: left;
    height: 22px;
    margin: 0 8px 0 0;
    padding: 2px 0px 0 0;
    width: 24px;
}

.title {
    display: inline-block;
}

Upvotes: 0

Related Questions