1

I've been creating a page for the last few days and have had this odd gap between the sections I've used. I have them contained in a div named wrapper but even within the div there is about a line's height gap between the top of the div and the start of the section. Further down the page there are also large gaps between the sections.

I can't seem to find a way to change this without messing with the top-margin but even then that is quite a 'hacky' way of doing it.

Here's the code to show I really haven't done anything (as far as I can tell) to the attributes.

section{
    height:10px;
    min-height: 400px;
    background: rgba(0, 0, 0, 0.5);
    border-bottom: 5px solid rgba(0, 0, 0, 0.5);
}

#wrapper{
    padding: 10px;
}

Here's the JSFiddle if that helps explain what I mean: http://jsfiddle.net/L6qeyhsv/

I thought it may be the default values of section but that wouldn't explain the gap between the top of section at the top of #wrapper

Thanks

3 Answers3

3

I have updated your fiddle,

You needed to remove the margin reset your <h1> to 0. A good way to test this is by using developer tools, highlighting the element and seeing what default margins and paddings are applied to the element.

Fiddle: https://jsfiddle.net/L6qeyhsv/5/

Halfpint
  • 3,967
  • 9
  • 50
  • 92
  • If you want to set your own spaces, set the margin to be larger. You can use `margin-top`, `margin-bottom`, `margin-left`, `margin-right` – Halfpint Feb 20 '15 at 20:52
2

You have to reset default <h1> margin.

section h1 {
  margin: 0;
}

Fiddle: http://jsfiddle.net/L6qeyhsv/3/

A side note, you can't have multiple ids with the same name, they must be unique.

Reference: Element identifiers: the id and class attributes

emmanuel
  • 9,607
  • 10
  • 25
  • 38
  • 2
    This is the correct answer, though it may be a bit hard to understand why this helps without a basic understanding of [Margin Collapsing](https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing). To those not familiar, it's an important concept. – James Montagne Feb 20 '15 at 20:48
  • That was embarrassingly simple. Thank you. I think I put the ID in when I first started the page with just one section. Must have forgot it was there – chrispollock Feb 20 '15 at 20:49
2

If by chance you want to avoid removing the margin from your h1 (which honestly you can and should remove and replace with padding either way), you can use a common clearfix hack to solve this:

section:before,
section:after {
    content: " ";
    display: table;
}

This works by essentially adding "first" and "last" elements which aren't affected by margin collapse. A longer explanation can be found here.

Jesse Kernaghan
  • 4,544
  • 2
  • 18
  • 25