Strae
Strae

Reputation: 19445

CSS3: keeping :after and :before elements aligned with the element's height

Im having a big headcache with a header design:

enter image description here

Here the demo: http://jsfiddle.net/uGECm/

The idea is to have the gray label that 'wrap' the element; However, the label's height is unknow (it can vary by its content) - my problem is that the 2 pseudo-elements made like triangles get a wrong position if the labels change the size, this becose they're position is relative.

Any idea?

ps: im looking for a no-js and no-images solution.

Upvotes: 3

Views: 108

Answers (3)

Matt Coughlin
Matt Coughlin

Reputation: 18906

  • Use absolute rather than relative position for :before and :after
  • Apply bottom:-10px; to both
  • Apply left:0; and right:0;, respectively.
  • Remove the float. Floating has no effect on an element with absolute position.

Updated jsfiddle demo.

section h2:before,
section h2:after {
    content: '\0000a0';
    width: 0;
    height: 0;
    position: absolute;    
    bottom: -10px;
    display: block;
}
section h2:before {
    border-left: 10px solid transparent;
    border-top: 10px solid #323232;
    left: 0;
}
section h2:after {
    border-right: 10px solid transparent;
    border-top: 10px solid #323232;
    right: 0;
}

Upvotes: 1

Jezen Thomas
Jezen Thomas

Reputation: 13800

section h2:before, section h2:after {
    width: 0;
    height: 0;
    display: block;
    position: absolute;
    bottom: 0;
    margin: 0 0 -10px 0;
}

section h2:before {
    content: '\0000a0';
    border-left: 10px solid transparent;
    border-top: 10px solid #323232;
}

section h2:after {
    content: '\0000a0';
    border-right: 10px solid transparent;
    border-top: 10px solid #323232;
    right: 0;
}​

Here's a fork with some further CSS formatting: http://jsfiddle.net/bqXeJ/

It's worth taking a look at a style guide like the one I wrote here, and also, if you use Lea Verou's prefixfree.js, you can skip writing declarations for each browser vendor.

Upvotes: 3

kevingessner
kevingessner

Reputation: 18985

You can position the pseudoelements absolutely. Since section h2 is position: relative, setting them to top: 100% will keep them stuck at the bottom, regardless of the parent's size:

section h2:before, section h2:after {
  position: absolute;
  top: 100%;
}

Upvotes: 1

Related Questions