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

本小妞迷上赌 提交于 2021-02-11 12:36:05

问题


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?


回答1:


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>



回答2:


Did you account for the browsers preset margin and padding. Try resetting them.

body{
margin: 0;
padding: 0;
}


来源:https://stackoverflow.com/questions/40197341/why-does-my-float-elements-not-working-properly-at-40-60-width-settings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!