0

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:

<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>
Sam
  • 15,254
  • 25
  • 90
  • 145
  • 1
    Maybe your pseudolements have position: absolute but you forgot to add position: relative to the element? It's hard to guess without seeing the actual code. – Fabrizio Calderan Jun 29 '22 at 11:23
  • Thanks for your suggestion, updated question and added snippet. When I replace `absolute` with `relative`, then the layout breaks and the borders are placed right after the text, which is Not what I want, I want the border to be set at `1em` relative to the light blue box, on the inside. – Sam Jun 29 '22 at 11:27
  • 1
    *I want the border to be set at 1em relative to the light blue box, on the inside.* this is exactly the result. if you need to add more space between the borders and the text then increase the padding – Fabrizio Calderan Jun 29 '22 at 11:31

1 Answers1

1

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>
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • Thanks! This solves it. Can you please explain in one or two sentences in your answer WHY it is necessary to add `relative` to the parent html element? – Sam Jun 29 '22 at 11:33