Home > Back-end >  Trying to set body width and height to 100% so I can work with percentages but it ends up masking al
Trying to set body width and height to 100% so I can work with percentages but it ends up masking al

Time:12-15

I've never had this happen before and I can't understand why this is happening. I'm working in React. I basically have a parent component with its body's css:

body {
width: 100%;
height: 100%
}

That way I can work with percentages in my project. My child component has

#Navbar {
width: 100%;
height: 10%;
background-color: black;
}

But I cannot see the child component except if I set its position to absolute. Does anyone have any idea why this is happening? Thanks in advance for any help!

CodePudding user response:

In CSS, body refers to document.body, not the the body of a component. I don't know that you can set width and height on document.body... it doesn't make any sense really, as body is the top visible element in the dom.

Setting height = 80% or width=90% or whatever makes sense for sizing an element that is within another element. But body has no parentNode as such.

CodePudding user response:

I'm not very familiar with react but maybe try to set the #Navbar content property. This should work for vanilla CSS and I hope for React too:

#Navbar {
  width: 100%;
  height: 10%;
  background-color: black;
  content: ""
}

Hope this helps ;)

CodePudding user response:

Does your component have content ?

.body references the HTML's body not your component. You have to give it an id or className for it to work

I would also recommend to use the <nav> html node and simply do as it's semantically more correct

nav {
   color: red;
   etc...
}

Codesandbox

CodePudding user response:

Body height 100% fits its content, you need to set the height also to its parent container, html element

html, body {
  min-height: 100%;
}

Most of the time you want min-height to allow the page to scroll correctly. In your case, I'd recommend vh units instead:

#Navbar {
  height: 10vh; /* 10% height of the viewport */
}
  • Related