CSS: Overlapping two divs with unique classes and varying margins - Unexpected occurrence or intentional design?

One thing I'm curious about:

  1. Will the margins of two different divs merge if they have the same value when intersecting? It appears so!
  2. Do paddings not merge when two different divs intersect, even if they have the same value? It seems that way!
  3. When two different divs with different paddings intersect, will each div respect its own padding, resulting in a greater height/distance between them compared to using margins (since padding doesn't merge)? It seems likely!

Question: When two different divs with different classes intersect (margin bottom of div 1 with margin top of div2), will the div with the higher margin value use the previous div's margin and only add the difference? Is this the expected behavior?

Is there a tool available to measure/show visually the distance in pixels between two objects on a browser (divs/images/paragraphs, etc.)? Any Firefox/Chrome add-ons recommended?

.div1-margin {
margin: 32px 0;
background-color: #fcfcc0;
}
.div2-margin {
margin-top: 132px;
background-color: #c0fcf9;
}
.div1-padding {
padding: 32px 0;
background-color: #c5fcc0;
}
.div2-padding {
padding-top: 132px;
background-color: #ecc0fc;
}
h2.h2margin {
color: blue;
padding: 0!important;
margin: 0!important;
font-size: 18px;
}
h3 {
font-size: 18px;
color: green;
padding: 16px 0;
}
h2.h2padding {
color: red;
padding: 0!important;
margin: 0!important;
font-size: 18px;
}
<h2 class="h2margin">Here, div 2 has a margin-top of 132px and div 1 has a margin-bottom of 32px.</h2>
<div class="div1-margin">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
</div>
<div class="div2-margin">
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum portes factures. 
</div>
<h3>Will the total distance (space) above between div 2 and div 1 be 132px? (margins used)</h3>
<h2 class="h2padding">Here, div 2 has a padding-top of 132px and div 1 has a padding-bottom of 32px.</h2>
<div class="div1-padding">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
</div>
<div class="div2-padding">
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum portes factures. 
</div>
<h3>Will the total distance (space) above between div 2 and div 1 be 164px? (paddings used)</h3>

Answer №1

Margins can sometimes create an undesirable appearance in web design. How browsers handle margins is governed by CSS specifications.

When two consecutive elements have margin-bottom and margin-top, the margins are not always added together. The following rules apply:

  1. If both values are positive, only the margin from the element with the higher value is considered.
  2. If both values are negative, only the margin from the element with the lower (more negative) margin is used.
  3. However, if one value is negative and the other is positive, both margins are added together (subtracting the negative from the positive), resulting in the combined margin being applied.

In instances where only positive values are used, like in your example with margin-bottom and margin-top, the margins do not combine as per the specification. Padding, on the other hand, is not subject to these rules, so the distance between inner elements is simply the sum of the padding values.

Many grid frameworks utilize padding for creating spacing between elements rather than margins for this reason.

For a more detailed explanation, you can refer to the blog linked here: https://css-tricks.com/what-you-should-know-about-collapsing-margins/

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

The width of my root container does not display at a full 100% in mobile dimensions

After creating a simple React.js project, I set up the folder structure using `npx create-react-app`. Additionally, I added some styling with `* { margin: 0; padding: 0; box-sizing: border-box }`, and specified background colors for the body and #root elem ...

I am looking to conceal an element as soon as a list item is scrolled into view and becomes active

Is it possible to hide a specific element when the contact section is activated on scroll, and have it visible otherwise? How can this be achieved using Jquery? <ul class="nav navbar-nav navbar-right navmenu"> <li data-menuanchor="ho ...

Border extends across two separate rows

Let me illustrate my issue with a specific example where I am utilizing a single column with a rowspan: <table border="1" style="width:300px"> <tr> <td rowspan="2">Family</td> <td id="jill">Jill</td> <td>Smi ...

Positioning a designated div directly above a designated spot on the canvas

I'm grappling with a challenge in my game where the canvas handles most of the animation, but the timer for the game resides outside the canvas in a separate div. I've been struggling to center the timer around the same focal point as the squares ...

Typewriter Effect: The caret is advancing too quickly

I am trying to achieve a typewriter effect on my text, but the blinking cursor is extending further than the actual text. See Image for Problem Here is the code I am using: HTML: <div class="title"> <h1>Hi, I'm ConnerDE< ...

What is the method for ensuring that the delete functionality is displayed within the same row?

In my division, there are options for names and deletion. It is displayed on my website as: 1.jpg delete The HTML code for the division is: <div id="files1" class="files"> <b class='dataname' >1.jpg</b> <span cla ...

When hovering, the CSS border-bottom should extend

I am looking to create an animated border effect. When hovering over the link, I want the border-bottom to extend seamlessly from left to right. After much searching, I am still unsure what this effect is called. Below is the code I have: .a{ width ...

What are the best methods for placing content within a box and ensuring it is responsive?

Having trouble solving a simple problem that seems to have an easy solution. The code I'm working on is meant to display multiple bubbles with similar content, but the text gets distorted due to using strange margin values to fit a specific resolution ...

"Effortless alignment: Centralizing CSS styling across the entire

I need help placing a loading spinner in the center of my screen, ensuring it works on both mobile and desktop devices. Here is my current CSS code: .spinner { width: 100px; height: 100px; position:absolute; top: 50%; left: 50%; margin: 100px ...

Eliminating an unwelcome gap between two div elements

I couldn't find anything on Google, so I searched this site and came across a similar topic Unwanted space between divs. I tried applying margin:0px; in several places, but there is still space between the two divs. Here's my HTML: <!DOC ...

JavaScript button mouse enter

There seems to be an issue with this code. The button is not functioning properly after hovering over it, even though it was copied from the instructional website where it works fine. <html> <head> <title>Button Magic</t ...

Eliminate the standard cell padding in nested HTML tables

In my setup, there is a parent table where each td tag in the tr tag contains a child table. Specifically, as shown in the example with Data WS-C3.... in the picture. [![<table class="table table--bordered table--nostripes table-top"> <thead& ...

How to set a canvas as the background of a div element

Check out my code snippet below: <!DOCTYPE html> <html> <body> <div id='rect' style='width:200px;height:200px;border:1px solid red'> </div> <canvas id="myCanvas" style="borde ...

Choosing an element that does not have a particular string in its colon attribute name

In my code, I have multiple elements structured like this: <g transform="matrix"> <image xlink:href="data:image/png" width="48"> </g> <g transform="matrix"> <image xlink:href="specific" width="48"> </g> <g tran ...

How to automatically close the menu on a Wordpress theme after clicking a link

I am currently using a Wordpress theme named ichiban, which can be viewed by following this link. Within this theme, I have created custom menu items that are designed to link directly to different sections on the same page. However, I am encountering an i ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

What is the best way to halt Keyframe Animation once users have logged in?

To enhance user engagement, I incorporated keyframe animation into my login icon on the website. The main objective is to capture the attention of visitors who are not registered users. However, once a user logs in, I intend for the keyframe animation to c ...

Loading Web Applications Screen

My web app contains multiple tree views. Upon loading the page, I first see the unordered lists before the styling of the trees is displayed in the DOM after a brief delay. Is there a method to mask the web app with a spinner placed in the center of the s ...

The Width of Material UI Divider

Currently seeking a method to increase the line thickness of the Material UI Divider, whether by stretching horizontal lines vertically or stretching vertical lines horizontally. I have reviewed the documentation for Material UI v5 on https://mui.com/mate ...

Mastering the Art of Harnessing External Templates in Meteor Mantra

I have been diving into the Mantra style guide () in order to integrate it with meteor. What confuses me is determining the "right" approach for using external templates with meteor and mantra. Specifically, I'm unsure about handling CSS and JS files. ...