The reason for this issue is due to the default styles applied by the browser's user agent stylesheet, which adds styling to certain elements. To resolve this, it is recommended to use a reset css.
Regarding the initial question about the space appearing when using float, it is because the float contains the default margin of the h1
. This behavior is explained further in the documentation available at here
The float CSS property positions an element on either the left or right side of its container, enabling text and inline elements to wrap around it. Despite being removed from the normal flow of the page, it remains part of the flow.
For more information, refer to: this link
Unlike div elements, the background color does not extend to the margin of its child elements; you must use padding instead. Margins are applied outside the element's border, while padding is applied inside.
Here is an example:
#container { height: 60%; width: 100%; background-color:green; }
#container h1 {margin: 100px 0;}
<html>
<head>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="container">
<h1>test</h1>
</div>
</body>
</html>
You can observe that the margin does not affect the background color of the parent but still takes up space.
Consider another scenario:
#container { height: 60%; width: 100%; background-color:green; }
#container h1 {margin: 0; padding: 100px 0;}
<html>
<head>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="container">
<h1>test</h1>
</div>
</body>
</html>
See the effect of adding padding to the h1
.
To have both elements aligned on the same line, remove the margin for the h1
:
#container
{
height: 60%;
width: 100%;
background-color:green;
}
#floatElement
{
top:0px;
height: 60%;
width: 50%;
background-color:red;
float:right;
}
#floatElement h1, #container h1{
margin-block-start: 0;
/*you can also use margin: 0 in short */
}
<html>
<head>
<link rel="stylesheet" href="css.css">
</head>
<body>
<div id="floatElement">
<h1 >this is a test inside the float element</h1>
</div>
<div id="container">
<h1>test</h1>
</div>
</body>
</html>