简体   繁体   中英

padding in background image aligned to the right

I have this html:

<div class="warning">
    <span>text text text</span>
</div>

and this css:

.warning
{
    background:#F2EEBB url(Images/warning_triangle.gif) no-repeat right center; 
    border:solid 1px red;
    margin:5px;
    color:#000000;
    font-weight:bold;
    padding-top:3px;
    padding-bottom:3px;
    padding-left:3px;
    padding-right:18px;
}

This is the result:在此处输入图像描述

The problem is that the background image that aligned to the right don't have padding between it and the border. How can I add a padding between the image and the border? (I cannot add elements to the div!)

Without any changes in html, and only a little change in css you can accomplish that .Try this css - I just change the position of the warning icon.

background:#F2EEBB url(Images/warning_triangle.gif) no-repeat 99.5% center;

<div class="warning">
    <span>text text text</span>
</div>


.warning
{
    background:#F2EEBB url(Images/warning_triangle.gif) no-repeat 99.5% center; 
    border:solid 1px red;
    margin:5px;
    color:#000000;
    font-weight:bold;
    padding-top:3px;
    padding-bottom:3px;
    padding-left:3px;
    padding-right:18px;
}

在此处输入图片说明

You could use the ":after"-psuedo class. That also makes your icon show up if a user prints the page. I made you an example .

为了使其与右侧的 18px 填充保持一致,您可以使用 calc。

background-position-x: calc(100% - 18px);

You can't specify a distance from the right or bottom edges for background images.

The easiest way to achieve the desired effect would be to add that space in the image itself. So you'd add a few pixels of empty space to the right side of warning_triangle.gif. That way, when you position it to the right side of your div, the empty pixels will be aligned on the right edge while the visible triangle will appear a few pixels away from the edge.

EDIT:

Using the :after pseudo-element as Per suggests is a clever solution that I was not aware of. Just remember that :after is not supported by IE 7 and earlier. So if you need to support these older browsers, this may not be the best solution.

您可以根据您在设计中想要多少空间在 photoshop 中剪切该图像

My solution:

article {
    padding: 0px 152px;
    background: transparent url('img.png') no-repeat right 152px top;
}

Works for IE9 and later.

Find below the code for ReactJS:

background: `url(${Background}) white no-repeat 97%`,

or

backgroundPositionX: '97%',

Setup your css in this way

background-color: #F2EEBB;
background-image: url('http://confluence.jetbrains.net/download/attachments/33436/warningIcon.png');
background-position: right;
background-repeat: no-repeat;

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM