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

To calculate the sum of input field rows that are filled in upon button click using predetermined values (HTML, CSS, JavaScript)

Greetings for exploring this content. I have been creating a survey that involves rows of buttons which, when clicked, populate input fields with ratings ranging from 5 to -5. The current code fills in one of two input fields located on opposite sides of ...

The transition effect of changing opacity from 0 to 1 is not functioning properly in Firefox

Having some trouble with this animation not working in Firefox. I'm triggering the animation using JavaScript after a delay like so: document.getElementById('my_id').style.webkitAnimationPlayState = "running"; I've also attempted: s ...

Utilizing cookies to track the read status of articles - markers for reference

Currently, I am in the process of developing a website and am interested in implementing a feature that allows users to track which articles they have read. I am considering adding a small circle next to each article heading to signify whether it has been ...

Sliding Toggle: Panel Revealed with Button Slide

Currently, I am working on implementing a jquery slide tab feature. The functionality is working fine on button click. However, I want the button to stick with the panel and slide along with it. At the moment, the button remains fixed while the panel slide ...

SQL Query: Change text color based on the result number retrieved

After executing my SQL SELECT statement, I want to display every record in a div using a While statement. I would like the divs to alternate in color, for example: Result 1 = white div Result 2 = grey div Result 3 = white div Result 4 = grey div. I am un ...

Challenges experienced during the process of uploading a website to the server

I seem to have encountered an issue where the Navigation background image is missing after uploading my website onto the server. Surprisingly, everything else seems to be working perfectly. What could possibly be the cause of this discrepancy? navbar-de ...

In what way is the background-color of WindowInfoBackground utilized?

I attempted to implement background-color : WindowInfoBackground;. The property background-color : WindowInfoBackground; allows for the assignment of the system color to the background-color attribute. Despite using this particular value, the backgroun ...

Ruby Thin Server: An Unexpected ActionView Template Error

Encountering an issue when trying to deploy my project on Amazon Web Services and accessing the domain. ActionView::Template::Error (Command 'java -jar /home/ubuntu/.rvm/gems/ruby-2.1.10@silk/gems/yui-compressor-0.12.0/lib/yui/../yuicompressor-2.4.8 ...

css effect of background image transitioning on mouse hover

Is there a way to have an element on my webpage with a background image that follows the movement of the mouse when hovered over? I want it to be similar to this website: This is the HTML code I currently have: <section id="home" data-speed="3" data-t ...

Compiling SCSS to CSS in Vue.js is a breeze

I am working on a vue js project that includes scss files. My goal is to compile these scss files into css and store them in the public folder. How can I achieve this? Should I make changes to the vue.config.js file? const path = require('path'); ...

Using jQuery UI to create sortable lists that are connected and have hidden overflow features

How can I hide overflow from two fixed-height divs containing sortable lists connected to each other without affecting their connection? For example, if overflow is set to hidden, the list item doesn't display when dragged outside of the div. I' ...

Encountering a 404 error while loading CSS in a Django application

I'm currently in the process of developing a chatbot application. I'm encountering issues with loading the CSS for the frontend using django's static data load feature. Here are the file paths: CSS path: C:\Documents\Django_Works ...

Achieving the grid-column property as you navigate deeper into the tree

Currently, I am in the process of integrating a CSS design that utilizes grid and grid-column into my Angular application. The design itself is quite effective, structured similar to this: .grid { display: grid; grid-template-columns: repeat(3, 1 ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

The functionality to Toggle submenus within a navigation menu using jQuery is not performing as anticipated

I implemented a horizontal menu using CSS, HTML, and jQuery. Clicking on a menu item displays a sub-menu. The issue I'm facing is that when one submenu is open and I click on another menu item, the new submenu opens but doesn't hide the previous ...

Experiencing problems with malfunctioning javascript tabs

As a beginner user and coder, I'm currently working on creating a portfolio website. I had the idea to implement tabs that would allow for content swapping, but unfortunately, I'm having trouble getting the JavaScript to function correctly. I at ...

The Visualforce page is not displaying page breaks correctly for cells with rowspan in the table

Having encountered a similar issue to this question: table rowspan page break On my Visualforce page, I have an HTML table with a custom rowspan in one column (varies based on the number of spanned rows) and I'm experiencing a styling problem (see is ...

CSS selector that targets elements within a specified parent element

Imagine a scenario where there are numerous divs in an HTML document, like the three examples provided below: <div id="1"> <p>hi</p><p>Peter</p> </div> <div id="2"> <p> hola</p><p>Peter&l ...

When the React button is clicked, it displays a stylish blue border

Hey there, I'm currently working on a project using React and facing an issue with some buttons I've styled. Whenever I click on them, they show a strange blue border that I can't seem to get rid of. I've tried setting border:none !impo ...

Manipulate classes based on scrolling (Wordpress)

Trying to manipulate a widget by adding and removing classes based on user scroll behavior has proven to be quite challenging. Specifically, I aim to add one class when the user scrolls down by 50px and remove it when they scroll back up. Website: Check o ...