Space between HTML tags

Asked

Viewed 1,816 times

1

I’m a beginner in HTML and CSS development, and I’m having a hard time understanding why between html tags is a space. As in the following example where I have a header, a div and a footer with different colors to facilitate the visualization, and between them there is always a white line. In such cases I would have to work with negative margin to correct this ?

body{
margin: 0;
}

header {
background-color: #333333;
color: white;
}

div {
background-color: red;		
}
		
footer {
background-color: #000000;
color: white;
}	
<header class="top-header">
<h1>Header</h1>	
</header>
	
<div class="top-content">
<h1>Main Content</h1>
</div>
	
<footer>
<h1>Teste</h1>
</footer>

  • 1

    This happens because browsers use default values on each element. Press F12 and Inspecione the element H1. You will see that it already has some predefined values. To get around this you can use the technique of CSS Reset or Normalize

  • As already commented, browsers have some default values, as well as the tag body the h1 also has a default margin. To remove it just set margin: 0; as it did in the body

1 answer

1


It’s like Valdeir said in the comment. Several HTML elements have CSS defauld values that can even vary from Browser to Browser, so elements like radio Buttons, input, and selects are different between Firefox, Safari, or Chrome.

If you are interested here you have a complete list of all HTML elements and their values default https://www.w3schools.com/cssref/css_default_values.asp

In the case of H1 in the Chreme for example, the user-agent(default browser style) puts the following values in the element

h1 {
    display: block;
    font-size: 2em;
    -webkit-margin-before: 0.67em;
    -webkit-margin-after: 0.67em;
    -webkit-margin-start: 0px;
    -webkit-margin-end: 0px;
    font-weight: bold;
}

If you inspect the H1 will see that it looks like this. The orange color is the margin that the element has by default

inserir a descrição da imagem aqui


Application example

If you take the shores of H1 will see that the divs stick together like you want.

body{
margin: 0;
}

header {
background-color: #333333;
color: white;
}

div {
background-color: red;		
}
        
footer {
background-color: #000000;
color: white;
}
/* romeve as margens do h1*/
h1 {
    margin: 0;
}
<header class="top-header">
  <h1>Header</h1>	
</header>
    
<div class="top-content">
  <h1>Main Content</h1>
</div>
    
<footer>
  <h1>Teste</h1>
</footer>

TIP: Run a quick test, get the code above and wherever <h1> place <p> and see that the white spaces will return. This happens because so does the h1 the tag p also has margins by default

Browser other questions tagged

You are not signed in. Login or sign up in order to post.