0

Given a page with three block elements below each other (here: header, main and footer), I'd like to ensure that there is no vertical margin between the three elements. The problem is that the content of the main element is generated (using a templating language) and I cannot make too many assumptions about the contained markup.

Consider this example: note how I already explicitly omitted the bottom margin of the caption and the top margin of the first paragraph. Alas, using main > *:last-child won't work for the p nested in a li element. Is there a way to generalise this such that a margin of e.g. a p nested in a li is omitted, too?

header {
  background-color: red;
}

main {
  background-color: green;
}

footer {
  background-color: blue;
}

h1 {
  margin-bottom: 0
}

main > *:first-child {
  margin-top: 0
}
<header>
  <h1>
    Hello
  </h1>
</header>
<main>
  <p>
    Some content
  </p>
  <ul>
    <li>
      <p>
        Some list item
      </p>
    </li>
  </ul>
</main>
<footer>
  There should be no white gap above!
</footer>

I'd like the main element to have no margin at the bottom whatsoever (not even by a nested element such as the p elements here), such that the footer element comes right below it.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207

1 Answers1

0

I think you can do this for your specific case. May be with other content in main other problems could be appear.

header {
  background-color: red;
}

main {
  background-color: green;
}

footer {
  background-color: blue;
}

h1 {
  margin-bottom: 0
}

main > *:first-child {
  margin-top: 0
}
main *:last-child {
   margin-bottom: 0;
}
<header>
  <h1>
    Hello
  </h1>
</header>
<main>
  <p>
    Some content
  </p>
  <ul>
    <li>
      <p>
        Some list item
      </p>
    </li>
  </ul>
</main>
<footer>
  There should be no white gap above!
</footer>
Alberto Rhuertas
  • 733
  • 4
  • 12