Define the size div of its background image

advertisements

Is it possible with CSS/HTML to resize some box to match exactly it's background image size? Without using javascript.

For instance let's say I have a simplest div:

<div class="image">TEST</div>

.image {
    background-image: url(http://placehold.it/350x150);
    width: 350px;
    height: 150px;
}

And I would like to resize it to those 350x150 dimensions without hardcoding those values. Also I cannot put any content inside this div.

http://jsfiddle.net/5Dane/

EDIT: I see a lot of answers I already was aware of, thank you for them, but that's not the solution here unfortunately. Below I'm explaining why I need such functionality.

What I'm trying to do is a form with steps (buttons previous and next). In session I hold all the values the user has input but there are some buttons which will add more functionality for the user (like multiple dynamically added rows for data). I'm doing it with jQuery of course, but I want the form to be able to work when there is no java script enabled.

Now to the point - I was trying to find out how to tell the difference which button the user has clicked. The case is all my submit buttons need to be images and the simplest solution <input type="image"/> doesn't send info about the button clicked with POST data. That's why I came to this solution:

<input class="submit_img" type="submit" style="background-image:url(http://placehold.it/108x23); width:108px; height: 23px;" value=" " name="some" />

/* Submit button with image */
input.submit_img {
    font-size: 1em;
    border-radius: 0px;
    box-shadow: rgba(0, 0, 0, 0.15) 0 1px 1px;
    border: solid 0px #000000;
    cursor: pointer;
}

http://jsfiddle.net/XRvqV/

This way my form will submit all the data AND I will know which button the user clicked. Also the button looks fine, like it should look. I was wondering though if it was possible to make it a little more portable - my buttons all have different widths for different functions. Can someone suggest another approach here?


No, you can't. CSS is not aware of the the image size. You can do it easily with JQuery.

JQuery exmaple

$(function(){
    var bg = $("div.image").css('background-image');
    bg = bg.replace('url(','').replace(')','');
    var newImg = new Image();
    newImg.src = bg;
    $("div.image").css("width",newImg.width);
    $("div.image").css("height",newImg.height);
});