How about placing one element above another? What sets apart using the margin property versus the position property for achieving this effect?

As I pondered the concept of stacking context, a question arose in my mind. Through my readings, I learned that by not applying any CSS properties that create a stacking context (such as position), it is possible to stack elements on top of each other using negative margins. For instance, you can have three divs where the third one sits atop the second and first, while the second one sits on top of the first. So far, so good.

My query is this: if we maintain the hierarchy of the three divs without altering it (with the third on top of the second and first, and the second on top of the first) using either negative margins or a CSS property like position, what differences might emerge? Could this impact responsiveness or any other aspect?

I've included some code for reference below so you can better grasp the scenario. Feel free to toggle between the different CSS code blocks within the comments line. The outcome remains the same!

.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border: 1px solid black;
width: 400px;
height: 400px;
}

.container div {
border: 1px solid black;
width: 50px;
height: 50px;
}


/*Effect with POSITION*/
.container :nth-child(3) {
background-color: palegoldenrod;
position: relative;
bottom: 10px;
left: 10px;
}

/*Effect with negative MARGIN*/
/*.container :nth-child(3) {
background-color: palegoldenrod;
margin-top: -10px;
margin-left: 20px;
}*/
<div class='container'>

<div></div>
<div></div>
<div></div>

</div>

Thank you!

Answer №1

When you remove the "negative margin" rule from container2 and the "position relative" rule from container1, the difference becomes apparent.

In container1: using position relative pushes the third box downward.
In container2: applying negative margin only moves the box while the third box remains in place.

<div class="mother">
  <div class='container'>

    <div></div>
    <div><span>hover on me</span></div>
    <div></div>

  </div>

  <div class='container2'>

    <div></div>
    <div><span>hover on me</span></div>
    <div></div>

  </div>

</div>
<style>
  .mother {
    display: flex;
    flex-direction: row;
    width: 500px;
  }
  
  .container {
    background-color: crimson;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 1px solid black;
    width: 250px;
    height: 250px;
  }
  
  .container2 {
    background-color: crimson;
    margin-left: 5px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 1px solid black;
    width: 250px;
    height: 250px;
  }
  
  .container div {
    font-family: helvetica;
    display: flex;
    text-align: center;
    align-items: center;
    color: gold;
    border: 1px solid white;
    width: 60px;
    height: 60px;
  }
  
  .container2 div {
    font-family: helvetica;
    display: flex;
    text-align: center;
    align-items: center;
    color: gold;
    border: 1px solid white;
    width: 60px;
    height: 60px;
  }
  /*Effect with POSITION*/
  
  .container :nth-child(2):hover {
    border: 2px solid lightseagreen;
    background-color: gold;
    position: relative;
    bottom: 10px;
    left: 10px;
    cursor: pointer;
    color: gold;
  }
  /*Effect with negative MARGIN
.container :nth-child(1) {
background-color: gold;
margin-top: -10px;
margin-left: 20px;
}*/
  /*Effect with POSITION
.container2 :nth-child(3) {
background-color: gold;
position: relative;
bottom: 10px;
left: 10px;
}*/
  /*Effect with negative MARGIN*/
  
  .container2 :nth-child(2):hover {
    border: 2px solid lightseagreen;
    background-color: gold;
    margin-top: -10px;
    margin-left: 10px;
    cursor: pointer;
  }
</style>

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

Synchronize two div elements with JavaScript

The demonstration features two parent divs, each containing a child div! The first parent div's child div is draggable and resizable using JQueryUI. There are events for both dragEnd and resizeEnd associated with this div. The goal is to synchronize ...

The v-bind class feature is failing to update the CSS on the object's properties

I'm attempting to dynamically modify the CSS of certain buttons based on object properties within a list. Below is the data I am rendering out, and despite following the documentation and ensuring my setup is correct, I seem to be overlooking somethin ...

5 Ways to Incorporate Font Awesome Icons into CSS Pseudo Elements

I'm attempting to incorporate FontAwesome icons into CSS pseudo elements. When I add the icon using HTML in the traditional manner, it works fine. However, I'm trying to integrate the fonts into a bootstrap accordion so that the icon changes whe ...

My keyframes seem to be malfunctioning, despite exhausting all my troubleshooting options

Could someone please help me figure out why the @keyframes rule is not working for me? I've tried adding -webkit- as a fix, but it doesn't seem to be helping at all. .keyframe { height: 15px; width: 50px; background-color: red; -webkit ...

Adjust the font size based on the dimensions of the container

I'm currently working on a script that dynamically sets the font-size based on the container's dimensions and the length of the text. This is what I have implemented so far. window.onload = function () { var defaultDimensions = 300; ...

Creating a NgFor loop in Angular 8 to display a dropdown menu styled using Material

I'm currently facing an issue with incorporating a Materialize dropdown within a dynamically generated table using *ngFor. The dropdown does not display when placed inside the table, however, it works perfectly fine when placed outside. <p>User ...

I have noticed that the Javascript code is being loaded prior to the completion of my HTML/CSS page for some unknown

I am completely new to the world of web development. I'm encountering an issue where my JavaScript code (specifically alerts) is loading before my HTML/CSS page has fully loaded. I've been using sample alerts to test this out, and ideally, they s ...

Clickable functionality disabled for form elements

I am encountering an issue with my system development task. The form elements appear to be unclickable, preventing any data entry in the fields. I have attempted moving the form tag above the first div in the code structure below as a troubleshooting step, ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

Attempting to locate the element's position using Selenium in Python

quem_esta_sacando = driver.find_elements_by_xpath("//div[@class='gameinfo-container tennis-container']/div[@class='team-names']/div[@class='team-name']") this is how I located the correct class, but now I want to ...

How to Implement Dotted Line Styling for Row Data in ReactJS with CSS?

I'm working on a condensed design with Reactjs Monday......................08:00 AM - 21:00 PM I have a lot of dots in the display above. How can I make it shorter without using so many dots? Entering numerous dots like this is not ideal for the webs ...

Show SVG in img tag on entire screen

I am facing an issue where my SVG image is not fully visible when displayed within an img tag on the browser's full screen. The bottom part of the image gets truncated, making it inaccessible to users. Below is the code snippet I have been using: ht ...

Tips for aligning text vertically in a column using CSS columns

Can text be vertically aligned in CSS columns? For example, aligning text to the top, center, or bottom within each column? I attempted to use vertical-align, but it doesn't seem to work on an unordered list or its items: html <div class="nav-ba ...

Navigating through a Collection of Pictures using Mouse Movement and Left-click Button

Trying to create a customized PACS viewer for scrolling through a series of CT head images. However, encountering an issue with scrolling through all 59 images. Currently, able to scroll from the first to the 59th image, but struggling to loop back to the ...

Don't forget the last click you made

Looking for a way to style a link differently after it has been clicked and the user navigates away from the page? Check out this code snippet I've been using: $(document).ready(function(){ var url = document.URL; function contains(search, find) { ...

versatile grid tiles with CSS flexibility

Trying to remove the svg elements while keeping the grid layout intact. The svgs are used to maintain a 1:1 aspect ratio for all tiles. UPDATE: Discovered a CSS Solution for this. Simply set aspect-ratio: 1 for the tiles. Is there an alternative soluti ...

The foundation grid system is not being implemented

How come my div is not affected by the foundation grid system: render: function(){ var {todos,showCompleted,searchText} = this.state; var filteredTodos = TodoAPI.filterTodos(todos,showCompleted,searchText); return ( <div> ...

Creating an XPATH Selector with SCRAPY

Having trouble retrieving the product name from a webpage: Struggling to locate XPATH that delivers a useful, specific result. Apologies for my initial question being quite basic :( class V12Spider(scrapy.Spider): name = 'v12' start_ur ...

Moving object sideways in 100px intervals

I'm struggling to solve this issue. Currently, I have multiple div elements (each containing some content) that I need to drag and drop horizontally. However, I specifically want them to move in increments of 100px (meaning the left position should b ...