Surprising <body> body movement caused by child's margin-top pushing it down

Whenever I come across HTML problems, they seem so simple that I almost feel silly asking about them. But here I am, clueless about why this issue is occurring.

In the following fiddle http://jsfiddle.net/o5ee1oag/2/, the body is being pushed down by a 50px margin on the header:

<body>
 <div id="background"></div>
 <header>
  <ul>
   <li>Button 1</li>
   <li>Button 2</li>
  </ul>
 </header>
</body>

As a result, setting div#background { position: absolute; } also gets pushed down. When inspecting with Firebug and applying background: red; to the body, the entire area turns red, including the margin.

1) Why is this happening when the body should be positioned 50px from the top?

2) How can I prevent the body from being pushed down in this way?

Your help would be greatly appreciated :).

Answer №1

To solve the issue, simply include display: inline-block; in your header CSS rule.

Check out the JSFiddle demonstration here - DEMO

header {
    display: inline-block;
    width:100%;
    height:100px;
    margin-top:50px;
    background:rgba(0, 0, 0, 0.4);
}

The problem arises due to margin collapsing:

When your header element is placed next to a body with a top margin of 50px, the margins combine and affect the positioning of the body's content as defined by the box model.

The div#background has a position: absolute; attribute which prevents margin collapsing. If you remove this attribute, the margin will apply to header without collapsing with the body - DEMO

Alternatively: You can also add top: 0px; to the div#background - DEMO

Learn more about margin collapsing:

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing. For more information, refer to Mozilla MDN

Explore further on collapsing margins behavior:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obscure silhouette enveloping the text enclosure

I'm a beginner in CSS and I need to create a text box like this: My supervisor asked for a shadow effect around the box when clicked. How can I accomplish this? Any assistance would be greatly appreciated. ...

"Discover the process of using Puppeteer to extract information from a website, even when dealing with input fields that are set

I'm attempting to replicate the structure of a website using puppeteer, and here's what I have so far: page = await this.createPage(browser); page.setContent(await originalPage.content()); The issue arises from input fields in the DOM that are ...

Download a complete website using PHP or HTML and save it for offline access

Is there a way to create a website with a textbox and save button, where entering a link saves the entire website like the 'save page' feature in Google Chrome? Can this be done using PHP or HTML? And is it possible to zip the site before downloa ...

One method I use to retrieve ajax data and assign it before rendering the view

Despite putting the ajax.get in the created function, I am still unable to retrieve the ap_name value. This issue is related to vue.js created: function () { ajax.get('/envs').then(function (res) { this.apName = res.AP_NAME; ...

Repositioning with Flexbox: shifting the middle element to a new line

I have a flex item that contains three divs. ┌────────────────────────────────────────┐ | WRAPPER | | ┌─────────┬─ ...

css media queries not taking precedence over default styles

Struggling to find a solution as no similar case was discovered!! To avoid adding a class name for each page, I am eager to utilize a generic class name as shown below: <div id="news"> <div class="news column">content 1</div> &l ...

Adjust the horizontal background-position transition for color change while scrolling using jQuery and CSS

I came across a fascinating website - - where the background-position changes on scroll() from a linear gradient with two colors to smoothly slide one color off the screen. While I grasped how they achieved the split colors using linear-gradient, I'm ...

How to make sure a bootstrap row fills the rest of the page without exceeding the height of the screen

In my Angular application, I am using bootstrap to create the following structure (simplified version). <div class="container"> <div class="header> <div class="mat-card> <!-- Header content --> < ...

Issue with Registration Form Redirection

This registration form has been created using a combination of HTML, PHP, and MYSQL. However, after filling out the form and submitting it, the page simply reloads. I'm unsure if there is an issue with my PHP or HTML code. I'm at a loss as to w ...

What's preventing the buttons from shifting positions?

Having some trouble with my Minesweeper Web Game setup. My buttons are stuck in place and won't budge. Can someone help me figure out what's wrong? Here's the code snippet I've been working on (FYI, using NetBeans 8.1 IDE) HTML: <! ...

Issues with script execution on Ajax tab

I'm currently using JQuery UI tabs to load content through Ajax. I have a situation where two tabs are supposed to load HTML content and execute a script to hide or show certain elements in the loaded content. However, I encountered an issue where the ...

Batch Script for Reading and Writing HTML files

My experience with writing DOS Batch scripts has been limited to basic tasks. However, I recently encountered a need to create a script that reads an HTML template file and generates a new file from it. I successfully managed to store the file data in a va ...

Setting the height of a div based on its own width: A step-by-step guide

Is there a way to dynamically adjust the height of a div based on its width using CSS and Bootstrap? I am looking to maintain an aspect ratio of 75:97 for the height and width of the div. .my-div{ height: auto; border-radius: 20px; padding: 20 ...

I can't seem to get the button to function properly, and it's really

I am having an issue with my "Let's Get Fit" button. When I hover over it or click it, the cursor doesn't change and it doesn't lead to index.html. I'm not sure why it's not working. .btn { display: inline-block; text-transf ...

Tips for creating a fixed element with ScrollTrigger and GSAP

How can I prevent the right div from jumping on top of the left div when using a scroll trigger to make the left div's position fixed? gsap.registerPlugin(ScrollTrigger); const tlfour = gsap.timeline({ scrollTrigger: { trigger: ".ma ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Mastering the art of CSS float and positioning techniques

Struggling with CSS positioning yet again. I'm trying to design a webpage with one main element in the center, surrounded by 10 others. The challenge is to maintain consistency across different screen sizes (excluding mobile). However, every time I r ...

Positioning a flex item to the right by using float

I am in need of assistance with my HTML layout. <div class="container"> <div class="sidebar" style="float:right"> Ignore sidebar? </div> <div> main content </div> </div> The container is set to have a flex disp ...

Placing an item inside the container without exceeding its vertical limit

Check out this jsfiddle - http://jsfiddle.net/az47U/3/ - where you'll find a Gallery div along with a Canvas div, both located within the body. These divs have been absolutely positioned to not affect the overall body height. I've set the body he ...

In a Twitter Bootstrap environment, the button cursor transforms into an I-beam when activated

After utilizing twitter bootstrap to construct a small blog site and integrating a third-party file upload application into the project, I encountered an issue. The CSS files in the file uploader style the "upload button," but when my cursor hovers over it ...