smoreno
smoreno

Reputation: 3530

Combine div border with image background

I want to achieve something like this:

Example

The width of the element is 100%. I will use only the centered corner and combine with border-top:

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

But the border stays inside the arrow. I tried up image background -1px to hide the border but it didn't work. How do I do this?

Upvotes: 2

Views: 3026

Answers (4)

Jeroen
Jeroen

Reputation: 63709

Interesting issue. Here's one contrived solution using the :before selector to absolute position the image over the border. See this jsfiddle for a working example. The relevant code is as follows:

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

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

Here's a screenshot of the result:

result of above code

Edit: the browser compatability for the :before selector tells us it's only supported in IE8 and higher. It's even worse though, because as far as I can tell the content: url(...) construct nor the background-image of a :before pseudo-element doesn't seem to work even in IE9. Fortunately, this should fall under graceful degredation...

Upvotes: 0

powerbuoy
powerbuoy

Reputation: 12838

Like Mash I'd use another element for the background, but unlike Mask I'd use the CSS :before or :after pseudo elements:

<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;
}

Upvotes: 0

tptcat
tptcat

Reputation: 3961

If you're already creating the image just make the entire thing your background image in the shape you want it. Make it long enough so it can adjust to whatever reasonable length element you might want to put it in.

Upvotes: 0

mash
mash

Reputation: 15229

I solved it with an extra container:

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/

Upvotes: 3

Related Questions