Home > Software engineering >  A problem with margin-top property in CSS
A problem with margin-top property in CSS

Time:11-13

So I made a HTML webpage, and it gave me this. enter image description here The structure is as follows (the accompanying CSS code is given below this one)

<header>
<h1></h1>
</header>
<section>
<article id="article1"></article>
<article id="article2"></article>
</section>
<section>
<article id="article3"></article>
</section>

The CSS code is this:

body {
  background-color: #ffffcc;
}

header {
  background-color: #6699ff;
  color: #ffffff;
  text-align: center;
}

section {
  width: 700px;
  clear: both;
}

article {
  background-color: #99ffff;
  padding: 10px;
}

h2 {
  background-color: #6699ff;
  color: #ffffff;
}

#article1 {
  float: left;
  width: 320px;
  height: 250px;
}

#article2 {
  float: right;
  width: 320px;
  height: 250px;
}

#article3 {
  width: 680px;
}

So I wanted to separate the two articles on top from the one on the bottom, and tried this:

<header>
<h1></h1>
</header>
<section>
<article id="article1"></article>
<article id="article2"></article>
</section>
<section style="margin-top: 10px">
<article id="article3"></article>
</section>

But I am getting the same result. I know what margin collapses are but this doesn't seem to be that. Can you please help me fix this?

Any help is appreciated.

CodePudding user response:

This behaviour is caused by the first section which only contains floated elements (i.e. the first two articles). Those will not be "wrapped" by the section's borders by default, so that section will therefore have a height of zero (use the browser tools to see that...), eventually causing the shown behaviour.

To avoid that, add overflow: auto; to the sections, or at least to those sections which only contain floated elements:

body {
  background-color: #ffffcc;
}

header {
  background-color: #6699ff;
  color: #ffffff;
  text-align: center;
}

section {
  width: 700px;
  clear: both;
  overflow: auto;
}

article {
  background-color: #99ffff;
  padding: 10px;
}

h2 {
  background-color: #6699ff;
  color: #ffffff;
}

#article1 {
  float: left;
  width: 320px;
  height: 250px;
}

#article2 {
  float: right;
  width: 320px;
  height: 250px;
}

#article3 {
  width: 680px;
}
<header>
  <h1></h1>
</header>
<section>
  <article id="article1">blabla</article>
  <article id="article2">blabla</article>
</section>
<section style="margin-top: 10px">
  <article id="article3">blabla</article>
</section>

  • Related