简体   繁体   中英

Text in front of CSS shape

I'm trying to get text to be on top (or in front of) a CSS shape. It works with border-bottom , but not with border-top (which is what I need it to look like). I am assuming that because the border-top property is set that it's pushing the text below the shape.

Not too sure how to get it to work correctly without having to use an image. I could have swore I've seen this done before, but I can't remember where.

Here's my fiddle: http://jsfiddle.net/ultraloveninja/W2SPd/

<h1>the trap</h1>
h1 {
    border-top: 100px solid red;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    height: 0;
    width: 100px;
}

You need 2 elements and 2 CSS styles. One for the text, and one for the background:

<h1><div>the trap</div></h1>

CSS

h1 {
    border-top: 100px solid red;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    height: 0;
    width: 100px;
}
h1 div {
    position: relative;
    top: -100px;
}

http://jsfiddle.net/vPt7h/

You can insert a span tag for the text and get:

h1 {
    border-top: 100px solid red;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    height: 0;
    width: 100px;
    position:relative;
}
h1 span {
   position: absolute;
    top: -100px;
}

Demo http://jsfiddle.net/W2SPd/10/

Feasible?

Simply create a new pseudo element :after and then style the pseudo element with the border styles instead :)

The advantages? You don't have to create new elements just for the style alone, or use unnecessary nesting/wrapping with no semantic meaning; and it is not an image-based solution. The drawback - requires browser support for pseudo elements, so may not work on old versions of IE... but that's not something you should worry about.

h1 {
    width: 100px;
    padding: 0 50px; /* To account for the left and right borders in pseudo element to ensure it lines up */
}
h1:after {
    content: " ";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    border-top: 100px solid red;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    z-index: -1; /* Displays pseudo element behind text */
    width: 100px;
}

See fiddle here - http://jsfiddle.net/teddyrised/W2SPd/11/

That's really a bad way to do it imo. It will still take up more space than needed and you're asking for potential problems down the road. Yes you can use the examples others have provided but if it were me, I would make the shape an image and use it as a background via CSS.

.myShape { background:url(/pathto/your/image.png); width:150px; height:100px; }

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