crixi
crixi

Reputation: 159

Padding on background image

I don't know if that is a best practice, but I used a background to put some kind of "ok icon" on a div.

My problem is that the background is setted to left and I can't put a padding there on the left side of the icon.

<div id="martu">
    <div class="text">
      dummy text dummy text dummy text dummy text dummy text
    </div>
</div>

CSS

#martu {
    background: url('image') no-repeat scroll 0px 8px #FFB9D9;
    padding: 5px 5px 5px 10px;
    margin-left: 5px;
}

.text {  font-size:17px;  padding-left:20px;}

Fiddle: http://jsfiddle.net/9up0kmou/

PS. I know that an option would be to put the image direct on that div, but my dilema is that if background images support paddings or margins.

Upvotes: 0

Views: 144

Answers (3)

mnsth
mnsth

Reputation: 2277

I'd probably do something like this myself. Using the pseudo-elements ::before and ::after is brilliant for placing icons and other things. That way, you get clean code, and you'd need less wrapping elements.

#martu::before {
    content: url("http://findicons.com/files/icons/2015/24x24_free_application/24/ok.png");
    float: left;
    margin-right: 10px;
}

Upvotes: 2

marked-down
marked-down

Reputation: 10408

You can use the background-position CSS property to adjust the location of your background image on your div, for example:

#martu {
   background-position:20px 20px; // where the values are x & y coordinates from the original default position
}

But no, short of actually adding whitespace to the image in an image editor (not a good idea, it would add unnecessary size to the file), there's no way of adding background-image-padding.

See this JSFiddle, where I have arbitrarily placed the tick icon in the middle of the element using background-position.

It's then a simple matter of adjusting the div padding to make sure the text doesn't overlap the image.

Upvotes: 2

evilham
evilham

Reputation: 336

Try this: http://jsfiddle.net/87obhb57/5/

Long story short: you can't have padding on the background image, so the trick here is to set up a background-color on the outer div that gives you the block appearance; setting up a padding on it that will provide the effect you are looking for.

#martu {
  padding: 5px;
  background-color: #FFB9D9;
}

And finally, setting the background-image of the inner div to what you want plus a padding-left that is big enough as to ensure that the text and the image won't overlap.

#martu div.text {
    background-image: url('something');
    background-repeat: no-repeat;

    padding-left:34px;
}

Upvotes: 1

Related Questions