1

I give up on this...

.wrapper {
     border: 1px solid #aaa;
     width: 300px;
     height: 300px;
     padding: 20px
}
h2 {
     border-bottom: 2px solid #ddd;
     display: block;
}
h2 span {
     border-bottom: 2px solid #f00;
     display: inline-block;
     margin-bottom: -2px;
}
<div class="wrapper">
  <h2><span>TITLE HERE</span></h2>
</div>

Please run the code snippet to see my objective. The length of the RED border is the length of the text title. How can I achieve that without having to add the span or any markup? I tried adding the gray border to pseudo-element ::before but it only doubles up the length of the red border, the gray border should fill the rest of the box. Please help me play with it. thanks!

wj R.
  • 359
  • 6
  • 18

2 Answers2

2

Here is an option using two pseudo-elements.

Both of the pseudo-elements are absolutely positioned relative to the top of the parent element. For the red border, the key is setting the parent element to inline-block so that it has a "shrink to fit" based width. Unfortunately, this method requires a hardcoded width for the second pseudo-element equal to the width of the .wrapper element.

Example Here

.wrapper {
    border:1px solid #aaa;
    width:300px;
    height:300px;
    padding:20px
}
h2 {
    display: inline-block;
    position: relative;
}
h2:before,
h2:after {
    content: '';
    position: absolute;
    left: 0; right: 0;
    top: 100%;
}
h2:after {
    border-bottom: 2px solid #f00;
}
h2:before {
    border-bottom: 2px solid #ddd;
    width: 300px;
}
<div class="wrapper">
    <h2>TITLE HERE</h2>
</div>
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Thanks, I'll try to adjust the wrapper if the gray border will follow its length. – wj R. Mar 19 '15 at 01:54
  • This is probably the best solution so far. I will just have to adjust the width of h2:before. Thanks dude. – wj R. Mar 19 '15 at 02:05
  • @wjR. Good idea, that's a great answer. +1. It's better than mine, I didn't think of adding the red border to the `h2` element itself. – Josh Crozier Mar 19 '15 at 13:17
1

I tried to push it some more and came up with this solution. I use index-1 and 2 for layer order. The solution of Josh is good but it doesn't support text-align property. I need text-align:right in particular. Without using z-index seems to be fine when running it here but when I apply it into my design, it won't work without it.

.wrapper {
    border:1px solid #aaa;
    width:500px;
    height:300px;
    padding:20px
}
h2 {
    display:inline;
    border-bottom: 2px solid red;
    z-index:1
}
h2:after {
    content: '';
    display:block;
    width: 100%;
    border-bottom: 2px solid #ddd;
    margin-top:-1px;
    z-index:2
}
<div class="wrapper">
<h2>TITLE HERE</h2>
</div>
wj R.
  • 359
  • 6
  • 18