开发者

:before and :after multiple border/background trick on images?

I've been using the :before or :after CSS trick (explained in this article: http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-multiple-borders-with-simple-css/) to achieve multiple borders and backgrounds. It works great on div elements but I noticed it doesn't work on images at all.

Here's my code:

.author img {
    position: absolute;
    left: 10px;
    background-color: #fff;
    padding: 3px;
    border: 1px solid #d0d0d0;
    width: 48px;
}

.author img:before {
    content: '';
    display: block;
    width: 80px;
    height: 16px;
    position: absolute;
    top: 开发者_C百科-17px; left: 0;
    background: red;
}

Is there a way to use this trick on images or will I have to wrap my images in an additional div?


You have to wrap an img because an img cannot contain a pseudo-element. When a :before and :after is used in CSS, what it is conceptually generating is this type of structure (say, with a div; note, this is just to illustrate what is being done, actual html elements are not created):

<div><pseudo-element:before />Actual div content<pseudo-element:after /></div>

The pseudo-elements are placed inside the element. But img tags (and input tags, and other such non-containers that do not have ending tags) do not have a place for "content" to go, including generated content from pseudo elements.


This works fine in DIVs, but an IMG wont work because it is overlapping the area where the inner borders are being applied. Luckily, there is a very simple workaround to this: contain the IMG inside a DIV.

<div><img src="pic.jpg" alt="1" height="200" width="200" /></div>

And apply the styles:

img {border: 2px solid red;}
div {border: 3px solid black; width:204px; height:204px;}

While you wont need to explicitly set the img height/width in your HTML, you still need to know what they are because DIV height/width is calculated like so: div h = img h + img borderx2; div w = img w + img borderx2

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜