The influence of 'overflow' values, aside from 'visible', on the block formatting context

Not quite like this particular question on Stack Overflow, mine doesn't involve float issues but rather troubles with applying margins to a block-level element's only child.

I encountered a dilemma while attempting to add a margin to an only-child of a block-level element:

#parent {
    background: rgba(255, 0, 0, 0.1);
}

#child {
    margin: 30px 0;
    padding: 20px;
    background: rgba(0, 255, 0, 0.1);
}
<div id="parent">
    <div id="child">Foo</div>
</div>

Despite the margin being applied, the parent's background fails to show up unless siblings are added before and after the #child, or by setting any non-visible value for overflow. The same example below shows how overflow affects it:

#parent {
    background: rgba(255, 0, 0, 0.1);
    overflow: auto;
}

#child {
    margin: 30px 0;
    padding: 20px;
    background: rgba(0, 255, 0, 0.1);
}
<div id="parent">
    <div id="child">Foo</div>
</div>

Referring to CSS2.1 Section 9.4.1 - Block Formatting Contexts, I discovered the following explanation:

Floats, absolutely positioned elements, block containers (like inline-blocks, table-cells, and table-captions) that aren't block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

The reasoning behind the "overflow other than visible" logic in this scenario seems perplexing to me. It appears that the margins are unaffected as the sole change is the background. Can someone clarify why using overflow: visible leads to such behavior?

Answer №1

In my response to the question you referenced, I detailed how overflow values other than visible create a new block formatting context due to constraints in float implementation, even though overflow may not seem directly related to floats initially.

While it is clear that floats and collapsing margins do not interact (never occurring together), the prevention of margin collapse through an element with specific overflow values is a secondary effect, as margins are expected not to collapse through any box establishing a block formatting context, as outlined in section 8.3.1. To quote:

  • Margins of elements creating new block formatting contexts (like floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.

This rule applies to both floats and elements with specified overflow values. The overflow itself does not directly impact margins.

In instances where both parent and child are block-level elements within the same block formatting context, they will naturally collapse unless certain conditions are met:

  • The top margin of an in-flow block element collapses with its first in-flow block-level child's top margin if there are no top border or padding on the element and no clearance on the child.

  • The bottom margin of an in-flow block box with auto height and minimum height of zero collapses with its last in-flow block-level child's bottom margin under specific criteria regarding borders, padding, and clearance.

This sheds light on why the parent's background doesn't extend until margin collapse is blocked off.

Answer №2

Your initial instances illustrate the collapsing of margins between parent and child elements. Essentially, the 30px margin of the child combines with the zero margin of the parent, resulting in the larger margin being applied to the parent. According to a quote:

In CSS, margins that are adjacent to each other from two or more boxes (regardless of whether they are siblings) can merge into a single margin. This merging is referred to as margin collapse, where the combined margin is known as a collapsed margin.

The same document also addresses the impact of overflow (as seen in your second example):

Margins of elements that create new block formatting contexts (such as floats and elements with an 'overflow' property other than 'visible') do not collapse with their in-flow children.

Answer №3

This explanation sheds light on a recurring issue I've come across regarding heights in web design. It seems that the height of the parent element is not always calculated based on the margins of its children.

If you take a look at this adjusted code snippet: http://jsfiddle.net/u6tQj/2/

#parent { background: #555;}
#child { margin:200px; background: #ccc; }

Even though the margins are applied to the child element, the height of the parent remains unaffected. However, by adding overflow or border properties, the parent's height adjusts accordingly. This inconsistency sometimes leaves me perplexed as to why parent elements don't always expand to accommodate their children.

While it may seem peculiar, there could be complex reasons behind conflicting rules when it comes to determining parent height. This could impact various browser layouts involving relative positioning of parent elements with absolutely positioned children, or using overflow auto/hidden, among other layout techniques. One can only imagine the challenges this would pose for the browser's layout engine, akin to how css selector specificity can be a source of frustration for developers.

A more intuitive solution would be to add padding to the parent element in order to adjust its height, don't you think?

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

Create a JavaScript variable every few seconds and generate a JSON array of the variable whenever it is updated

My variable, which consists of random numbers generated by mathrandom every second, such as "14323121", needs to be saved to an array for the latest 10 updates. function EveryOneSec() { var numbers = Math.random(); // I want to create an array from th ...

What could be causing the footer to not show up at the bottom of the page?

I've encountered an issue with my code where the footer appears to be stuck at the bottom of the h2_c div instead of the bottom of the .content div where it should be. I have tried using positioning but it hasn't resolved the problem. Thank You. ...

Unique design and elements featuring the `width: auto` property for custom fonts

In my current project, I am utilizing the popular 'Open Sans' font family. However, I am encountering a specific issue. The problem arises with buttons and other elements that have width: auto. Upon page load, these elements initially have their ...

Maintain the fixed position of the table header while scrolling

I am facing an issue with my table setup - I want the header to stay fixed while scrolling through the body. Here is how my table structure looks: <table> <thead> <tr> <th>Header 1</th> ...

Personalize or delete the spacing within an ion row

Currently, I am delving into the world of Ionic app development. Although I have grasped the concept of the Grid layout, I find myself hitting a roadblock when it comes to adjusting or removing spaces between rows 2 and 3 in my app interface, as illustrate ...

Display scroll bars over the position:absolute header

My container has content that exceeds its size in both directions. To see the issue, try scrolling horizontally and vertically on the table available here: The vertical scrollbar is visible as desired, except that it gets hidden behind the table header un ...

Updating Dropdown Selection in Angular 9 and 10

Is there a way to set attributes to "Selected" in HTML options based on a condition from a *ngFor loop in response.body of the component ts file? Below is the dropdown code: <select [(ngModel)]="customer.id"> <option *ngFor="let location of lo ...

What are the best practices for maximizing the efficiency of bootstrap-sass?

Currently, I am exploring npm modules and came across bootstrap-sass. After downloading the modules, I was seeking a solution to compile scss into the static folder of my application, as well as the js bootstrap files. However, after checking the npmjs do ...

Revamping Existing Styles: Making a Statement with `:after`

In my asp.net mvc application, I am facing an issue where the * symbol, representing a required field, and the ? symbol, representing help, are not both being displayed. The ? symbol seems to be overriding the * symbol, resulting in only one symbol being s ...

Toggle the visibility of a hidden div by clicking a button

After spending several days working on this project, just when I thought it was perfect, I had to completely restructure the entire page. Now I'm feeling stuck and in need of some help. The issue is that I have three images with buttons underneath eac ...

Sorting across several lists leads back to the initial list

I currently have multiple lists, with each list and item sharing the same class. For example: <ul class="cat_1"> <li class="cat_1">Item1</li> <li class="cat_1">Item2</li> <li class="cat_1">Item2</li> ...

Vertical Orientation in HTML

Would appreciate some assistance on creating a vertical text with HTML similar to the example in the linked screenshot. It needs to be straightforward and vertically oriented. Check out the screenshot for reference ...

The start-up process of AngularJS applications with Bootstrap

Curious about the predictability of the initialization flow in AngularJS apps? Want to understand the order of execution of different blocks within an HTML document? I came across a question on bootstrapping in Angular JS, but it didn't delve into th ...

Event handler for the MouseLeave event is not successfully triggering when dealing with anchor

When viewing a link to a Codepen, the issue is most noticeable in Chrome: https://codepen.io/pkroupoderov/pen/jdRowv Sometimes, the mouseLeave event fails to trigger when a user quickly moves the cursor over multiple images, resulting in some images reta ...

Using multiple conditions in SetEnvIf

I am trying to implement the SetEnvIf directive in my .htaccess file for handling multiple conditions and redirecting to a specific URL. The code I have written is as follows: SetEnvIf Remote_Host "^" press_flag=0 SetEnvIf Request_URI '/press/$&apos ...

The Unforeseen Consequences of Bootstrap Navbar CSS

I'm still learning CSS, so bear with me if I don't explain this issue correctly. Whenever I click on a navigation menu tab in Chrome or Safari, a mysterious blue rectangle appears. It doesn't show up in FireFox though. I'm not sure what ...

Mall magnitude miscalculation

I am currently experiencing an issue with Galleria and the Flickr plugin. Some images are displaying correctly, while others appear scaled and parts of them are cut off. How can I fix this problem? Below is the HTML code for the Galleria gallery on my web ...

Apply CSS3 attributes in real time

The for loop I have is functioning properly: <div id="page1div"></div> <script> list = " "; for (var i = 0 ; i < length ; i++) { list = "<h1 class='entriesdisplayed'>" + item(i) + ...

What is the best way to incorporate the :after pseudo-element in JavaScript code

HTML: This is my current code snippet <div class="one"> Apple </div> I am looking to dynamically add the word "juice" using JavaScript with the .style property. Is there an equivalent of :: after in CSS, where I can set the content in JavaS ...

Load jQuery to display the Bootstrap modal.ORUse jQuery to load and

My attempt to use the .load() function to display a bootstrap modal immediately on my page isn't working. The modal opens but cannot be closed afterward. The goal is to load a list of players in a modal whenever a team name with the class .team is cl ...