Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Add & Style Phantom CSS Borders to an HTML element using Pseudo Selectors ::before and ::after

I would like to have two borders, one left and one right set and realtive to 1em inside the <nav> element.

I succeeded by adding an extra HTML element which I then styled, however I find that not an elegant solution and want to achieve this in pure CSS using just ::before and ::after.

Undesired:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<nav>
  <div style="lines"></div>
  Content
<nav>

Desired:

<nav>
  Content
<nav>

I do Not want to add any extra HTML elements. I want the two borders placed 1em relative to the inside of the lightblue <nav> box.

My solution works partially, but for some reason the borders are "connected" relative to the entire HTML page, and not to the nav element.

What have I overlooked?

enter image description here

html {background: #EEE; margin: 10em}

body {background: #DDD; margin: 0 auto;}

nav{background: lightblue; height: 80vh; padding: 1em;}


nav::before, nav::after{
  content: '';
  position: absolute;
    height: 80vh;
    border-right: 2px solid #EEE;
    border-left: 2px solid #AAA;
}


nav::before{left: 1em; }
nav::after{right: 1em; border-bottom: none;
}
<nav>
Test
Test
Test
</nav>

>Solution :

Your pseudolements have position: absolute but you forgot to add position: relative to the nav element.

An element with position: absolute is positioned according to the first positioned ancestor (e.g with position: relative) or, if missing, to the root element

  html {background: #EEE; margin: 10em}

  body {background: #DDD; margin: 0 auto;}

  nav{
    background: lightblue; 
    height: 80vh; 
    padding: 1em 2em; 
    position: relative;
  }

  nav::before, nav::after{
    content: '';
    position: absolute;
      height: 80vh;
      border-right: 2px solid #EEE;
      border-left: 2px solid #AAA;
  }


  nav::before{left: 1em; }
  nav::after{right: 1em; border-bottom: none; }
<nav>
Test
Test
Test
</nav>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading