Escape from parent margin

I want a full with (of the backgrond) of the my Navbar, this nav is inside a Main tag with margins. But with nav: width: 100% don’t work, only stretches to the right. Heres my code:

CODEPEN: https://codepen.io/ricardorien/pen/XWgEjyL

<div class="main">
  <nav class="nav">
    <ul>
      <li>Lorem One</li>
      <li>Lorem Two</li>
      <li>Lorem Three</li>
    </ul>
  </nav>
  
  <hr/>

  <section class="section">
    <p>
      Lorem dolore ullam vel tenetur ratione atque explicabo aliquid quia.
    </p>
    <p>
      Lorem dolore ullam vel tenetur ratione atque explicabo aliquid quia.
    </p>
    <p>
      Lorem dolore ullam vel tenetur ratione atque explicabo aliquid quia.
    </p>
  </section>
</div>

CSS

* {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
}

.main {
  margin: 7em;
}

.nav {
  background: cornflowerblue;
  width: 100%;
}

ul { color: yellow; }

hr { background-color: red; }

in the way you are structuring your page you need position: absolute; on your nav element.

You need to have one thing in mind when adding widths with %, that % is relative to it’s parent. If the parent is 1000px wide, and you put an element (a nav for example) with 100% width your element will be 1000px too because is 100% of it’s parent. In the same way if you set a witdh of 50% your element will be 500px wide (50% of 1000px).

The only way to make en element bigger than it’s parent is by absolute positioning the element, but I suggest you try to avoid unless is necessary, is nothing fun dealing with too many absolute elements :laughing: .

Instead, you can re-think your html structure, removing the parent margin/padding to avoid the issue and use margins in the other elements, or even better moving your nav outside that container.

1 Like
1 Like

Thanks a lot. amazing explanation! Can you respond one more question? If i wanna have margins in every section of the page you suggest to write manually each everyone? i mean, NOT write body { margin 0 1em }

No, just how you did it first is fine, using a container (your main div) with margins, just the nav needs the full width, by placing it outside you wont have the issue, this will do the trick:
body
–Nav (no margin)
–container (margin or padding)
----all your sections (no margin).

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.