5120bee 5120bee - 1 year ago 56
CSS Question

Why does my float elements not working properly at 40% + 60% width settings?

I have the following CSS and HTML set:



html, body{
margin: 0;
}

header{
border: 1px solid green;
background-color: green;
height: 50px;
}

nav{
border: 1px solid red;
background-color: red;
height: 50px;
}

aside{
border: 1px solid yellow;
background-color: yellow;
height: 50px;
width: 40%;
float: left;
}

section{
border: 1px solid blue;
background-color: blue;
height: 50px;
width: 60%;
float: right;
}

<body>
<header>

</header>
<nav>

</nav>
<aside>

</aside>
<section>

</section>
</body>





But I'm confused as to how my
<aside>
and
<section>
are not side by side even after setting them to float properties. I set
<aside>
to
width: 40%
and
<section>
to
width: 60%
. Shouldn't they add up to
100%
and fill the entire webpage horizontally across?

Answer Source

This is happening because of 4px of extra space is being covered by borders in aside and section boxes. Just provide box-sizing: border-box to both;

html, body{
  margin: 0;
}

header{
  border: 1px solid green;
  background-color: green;
  height: 50px;
}

nav{
  border: 1px solid red;
  background-color: red;
  height: 50px;
}

aside{
  border: 1px solid yellow;
  background-color: yellow;
  height: 50px;
  width: 40%;
  float: left;
  box-sizing: border-box;
}

section{
  border: 1px solid blue;
  background-color: blue;
  height: 50px;
  width: 60%;
  float: right;
  box-sizing: border-box;
}
<body>
  <header>
    
  </header>
  <nav>
    
  </nav>
  <aside>
    
  </aside>
  <section>
    
  </section>
</body>