将div边框与图像背景相结合

时间:2012-08-18 14:58:28

标签: html css image background border

我想实现这样的目标:

Example

元素的宽度为100%。我将仅使用居中的角落并与border-top结合使用:

.element { 
border-top: solid 1px #ccc ; 
background: url('../images/arrow.png') no-repeat center top; 
}

但边界仍在箭头内。我试过up image background -1px来隐藏边框,但它没有用。我该怎么做?

4 个答案:

答案 0 :(得分:3)

我用一个额外的容器解决了它:

HTML:

<div class="first"><div class="second"></div></div>​

CSS:

.first {
    border-bottom: 5px solid #000;
    width:100px;
    height:100px;
    background-size: 20%;
    background-position:50% 105%;
    box-sizing: border-box;
}

.second {
    width:100%;
    height:104px;
    background: url(https://encrypted-tbn3.google.com/images?q=tbn:ANd9GcROusF7rh7H4mWpr8wQIllxWPAHHIShRyG62xp3qy2O4Av_NmNV) no-repeat;
    background-size: 20%;
    background-position:50% 100%;
}
​

jsfiddle:http://jsfiddle.net/AKpLT/

答案 1 :(得分:0)

如果您已经在创建图像,只需将整个图像设置为您想要的形状即可。使它足够长,以便它可以适应你想要的任何合理的长度元素。

答案 2 :(得分:0)

有趣的问题。这是一个设计的解决方案,使用:before选择器将图像绝对定位在边框上。有关工作示例,请参阅this jsfiddle。相关代码如下:

div {
    border: 1px solid red; /* For demo purposes it's red */
    position: relative;
}

div:before {
    content: url('http://i.stack.imgur.com/P3zMs.png');
    position: absolute;
    top: -1px;
    width: 100%;
    text-align: center;
    line-height: 1px;
}

以下是结果的屏幕截图:

result of above code

修改: :before选择器的browser compatability告诉我们它仅在IE8及更高版本中受支持。更糟糕的是,因为我可以告诉content: url(...)构造和a background-image:在伪元素之前,即使在IE9中似乎也不起作用。幸运的是,这应该归于优雅的降级......

答案 3 :(得分:0)

和Mash一样,我会使用另一个元素作为背景,但与Mask不同,我会使用CSS:before或:after伪元素:

<h2>Heading</h2>

h2 {
    border-top: 1px solid #ccc;
    position: relative;
}

h2:after {
    background: url(IMAGE);
    content: " ";
    display: block;
    width: WIDTH-OF-IMAGE;
    height: HEIGHT-OF-IMAGE;
    position: absolute;
    left: 50%;
    top: -1px;
    margin-left: -WIDTH-OF-IMAGE/2;
}
相关问题