Size div to fit background image

1,421 views
Skip to first unread message

Alan Lynn

unread,
May 17, 2012, 12:41:38 AM5/17/12
to compas...@googlegroups.com
If I want to use div with a background image instead of an <img>, I have to specify the dimensions of the image like so:

#div-image
    background-image: url('image.png')
    width: 10px
    height: 10px

But what if I change the image size? Then I need to change the css too. I want something that detects the dimensions of the image and specifies it for me. Something like this:

#div-image
    @include background-image(image.png)

Is this something Compass can do, and if so, what's the best way to go about it?

Eric Meyer

unread,
May 17, 2012, 1:49:22 AM5/17/12
to compas...@googlegroups.com
Compass has this, in several arrangements.

Here's one option:

background: image-url(image.png);
height: image-height(image.png);
width: image-width(image.png);

(see http://compass-style.org/reference/compass/helpers/)

Here's another:

@include replace-text-with-dimensions(image.png)

(see http://compass-style.org/reference/compass/typography/text/replacement/)

Cheers,
-e

Alan Lynn

unread,
May 17, 2012, 1:52:55 PM5/17/12
to compas...@googlegroups.com
That helps a lot. Thank you.

I went with the first option and put the 3 lines into a mixin so I only have to enter the image url once:

@mixin css-image($image_url)
    background-image: url($image_url)
    width: image-width($image_url)
    height: image-height($image_url)
Reply all
Reply to author
Forward
0 new messages