问题
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