Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double border with only one element

Tags:

html

css

I was trying to get a double bordered (underlined) header. First one is full width, second is just text width. Borders should overlap There is an easy solution with two elements nested like that:

<h1><span>Title</span></h1>

and css:

h1 {
    border-bottom: 1px solid red;
}

h1 span {
    display: inline-block;
    padding: 0 0 10px;
    margin-bottom: -1px;
    border-bottom: 1px solid blue;
}

Span has inline-block display property so it has right width.

I'm wondering if it's possible to get same effect with :after, :before selectors and only h1 element.

like image 321
Łukasz Pijet Avatar asked Sep 22 '13 23:09

Łukasz Pijet


1 Answers

It can be done. I've used vw units.

Take a look at this Working Fiddle

HTML:

<h1 class="SpecialBorder">Title</h1>

CSS:

*
{
    margin: 0;
    padding: 0;
}
.SpecialBorder
{
    display: inline-block;
    position: relative;
}
.SpecialBorder:before , .SpecialBorder:after
{
    content:'';
    position: absolute;
    left: 0;
    bottom: 0;
}
.SpecialBorder:before
{
    width: 100vw;
    border-bottom: 1px solid red;
}
.SpecialBorder:after
{
    width: 100%;
    border-bottom: 1px solid blue;
}

Explanation: the before & after pseudo elements are the ones that draw the borders. both of them are empty elements. with a certain width that causes their border to be visible.

they are absolutely position at the bottom of their <h1> parent.

before: responsible for the red border. so his width is set to '100%' of view port. after: responsible for the red border. so hes width is set to 100% of his parent (the <h1>), that's why the h1 is set to `display:inline-block;" (so it will span ony just as his content)

vw unit is supported by new browsers only.

notice that if you cant use vw units, you can still make something familiar to that. delete the display:inline-block; from h1 (causing it to span all the way again) change the width of before to 100% (to make it span all the way), change the with of after to some fixed value of your choice.

Edit: as thgaskell stated in th comment,

there's a bug where vw units don't update properly on webkit browsers when the window is resized.

Edit 2: for making elements to show after the title, you can use a <br /> tag, or clearing techniques like showed here.

like image 190
avrahamcool Avatar answered Oct 22 '22 06:10

avrahamcool