Home > Software design >  How to make a navigation bar ignore body padding in HTML/CSS?
How to make a navigation bar ignore body padding in HTML/CSS?

Time:02-05

I've set some padding in my 'body' tag, but want my top navigation bar to ignore it and extend across the entire page.

I've tried setting a fixed width (100%) and then using a negative padding and margin values, but it remains in the same position.

Here's what I think is the relevant code:

html {
    height: 100%;
    }
.topnav {
    background-color: rgb(15, 25, 75);
    overflow: hidden;
    width: 100%;
    float: right;
    margin-left:-100px;
    padding:0;
  }
body {
    /* background: linear-gradient(#9fdaff,#1b4c92); */
    background-color: rgb(255, 255, 255);
    height: 100%;
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
    padding-left:100px;
  }

the 'topnav' element is what I'm trying to get cover the entire screen.

CodePudding user response:

The padding in the body restricts every other element within the body to start from 100px from the left and so on. Solution:

  1. One thing you can do is that inside the body makes a div that encloses all other content of the body except the navbar and gives the body styling that you have stated above to that div it can solve the problem.

  2. Otherwise, if you want to go with the same code then add the following CSS to.topnav

    .topnav { position: absolute; left: 0; right: 0; z-index: 1; }

By setting the position absolute the element is taken out of the normal flow of the document and positioned relative to the nearest positioned ancestor element. Whereas, setting left: 0 and right: 0 aligns the element to the left and right edges of the ancestor, which in this case is the body. The z-index property is used to set the stack order of the element, making sure it is displayed on top of other elements. Elements with a higher index will be placed on top of elements with a lower index. Note: Z index only works on positioned elements ( position: absolute, position: relative, or position: fixed ). Also, remember to delete margin-left=-100px; from your .topnav else it will start from -100px from the left.

CodePudding user response:

You can try this:

.topnav {
    background-color: #00FF00;
    overflow: hidden;
    width: 100%;
    float: right;
    position: absolute;
    left: 0;
    padding:0;
  }

But notice that will make .topnav "float" on top of the other elements, so consider add padding to other elements to have some spacing with it.

You can see more in here: https://codepen.io/mhung912/pen/wvxNLJq

CodePudding user response:

I'm not sure I'm new too but try this:

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

CodePudding user response:

Add position: absolute; to .topnav:

.topnav {
  background-color: rgb(15, 25, 75);
  overflow: hidden;
  width: 100%;
  float: right;
  margin-left:-100px;
  padding:0;
  position: absolute;
}
  • Related