What is the best way to layer elements with different shapes on top of

My goal is to have the two squares on each side come together and overlap in the center of the wrapper. However, I'm facing an issue where one square drops down a level once they are brought together. I'm unsure if this can be fixed with jQuery or CSS.

To view my code, click here

$(document).ready(() => {
  $(".square").animate({
    backgroundColor: "red",
  }, 3000);

  $("#squareOne").animate({
    marginLeft: "+=45%",
  }, 800);

  $("#squareTwo").animate({
    marginRight: "+=45%",
  }, 800);
});
#wrapper {
  width: ...;
  margin: 100px auto;
  border: 1px solid black;
}

.square {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  margin: 10% 30px;
}

#squareTwo {
  position: relative;
  float: right;
}

#squareOne {
  position: relative;
  background: #fff;
}


}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <div id="wrapper">
    <div class="square" id="squareOne"></div>
    <div class="square" id="squareTwo"></div>
  </div>
</body>

Answer №1

To achieve overlapping squares, they must be positioned absolutely.

Next, there is a calculation involving the distance to be traveled...

$(document).ready(() => {
  $(".square").animate({backgroundColor: "red"},3000);
  
  // Calculate the slide distance
  // This involves half of the wrapper width minus half of the square width
  let distanceToTravel = $("#wrapper").width() / 2 - $(".square").outerWidth() / 2;

  $("#squareOne").animate({marginLeft: distanceToTravel},800);
  $("#squareTwo").animate({marginRight: distanceToTravel},800);
});
#wrapper {
  margin: 100px auto;
  border: 1px solid black;
  position: relative;
  display: flex;
  justify-content: space-between;
  
}
.square {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 10% 30px;
  position: absolute;
}

#squareTwo {
  right: 0;
}
<head>
  <meta charset="utf-8">
  <title>JavaScript</title>
  <link rel="stylesheet" href="styles/styles.css">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script src="scripts/fma_t5.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
  <div id="wrapper">
    <div class="square" id="squareOne"></div>
    <div class="square" id="squareTwo"></div>
  </div>
</body>

Answer №2

The issue lies in the excessive use of margin. Margin tends to displace other elements around it.
A better approach would be to utilize position: relative;, along with either left: 800px; or right: 800px;
This will prevent any unwanted shifting of elements on the page.

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 AJAX form submission is malfunctioning in CodeIgniter without triggering a page refresh

Hello everyone, I've been struggling to submit my form using ajax, but for some reason, it's not posting the values to my database table. This is my first time using ajax for form submission, so I'm not sure where I went wrong. Can someone h ...

Displaying incorrect results within the div container

I have been developing a website where a div element on a specific page displays values from a PHP file. Below is the PHP code responsible for rendering the information on the HTML: $output .= ' <div class="row text-left col-md-3 ...

Here is how you can include a date picker with the ability to choose the day, month, and year

Can someone help me create a datepicker with options to select days, months, and years? I've been able to find resources for selecting months and years, but I'm having trouble adding the option to choose specific days. If anyone has experience ...

When the page is zoomed in, the image exceeds the boundaries of the parent div

I attempted to position the div elements but did not achieve the desired outcome. .tab-vertical { border: 1px solid black; } <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

What is the best method for properly inserting images into a Vue Carousel 3D slider?

I'm currently exploring the Vue Carousel 3D documentation and I am having trouble displaying a single image on each slide. Let me elaborate: I aim to create a slider similar to the one shown in the Controls Customized example in the documentation. Th ...

Button Element Not Appearing in JavaScript/HTML

My current project involves creating a replication of the Windows calculator to practice JQuery and JavaScript. I have already set up all the HTML buttons for this basic calculator, but I am facing an issue where only the number "1" is displayed when click ...

Changing the position of the checkbox label to be above the checkbox

Can you help me with rearranging the checkbox label position to be above the checkbox instead of on the left side? I currently have the labels appearing on the left-hand side of the checkboxes, but I would like them to be positioned above the checkboxes. ...

Utilizing html2canvas in pdf-lib using JavaScript

Hey there, I have a few questions concerning the usage of html2canvas. Currently, I am delving into JavaScript and working on a platform aimed at generating budgets that can be downloaded in PDF format. My goal is to utilize html2canvas to capture a dynami ...

What sets apart the <script> tag with a type attribute from the standard <script> tag in HTML?

Similar Question: Is it necessary to include type=“text/javascript” in SCRIPT tags? While working on my HTML project, I noticed that the JavaScript code within script tags is evaluated even if the type attribute is not explicitly set to "j ...

Creating two tables in JavaScript and styling them with separate CSS designs

I am in the process of creating two tables dynamically using JScript. Instead of using the traditional method of separating them with assigned tags in HTML, I have approached the creation of the first table in a different way: function makeCells() { v ...

Can I input an array of values into a jQuery Knob for use?

Can I assign an array of values to my knob settings, like: 20,30,60,100,200,400,800 Is this feasible? Link to jQuery Knob GitHub repository ...

Exploring the DOM with jQuery

<p class="current" style="display: block; ">MD</p> <input type="text" class="hidden" value="MD" style="display: none; "> <p class="small hidden" style="display: none; ">MD, MBBS etc.</p> <a class="save-field-data btn hidden ...

Create a specific part of a webpage that can be scrolled through

In a unique way, I have designed a page where the only way to navigate is by simply clicking. To achieve this, I have implemented the following custom CSS: body{ overflow:hidden; } However, I have encountered a problem where I am unable to scroll to ...

Footer div is being covered by the page

I am currently working on a website built with "WordPress", and I have implemented a mobile footer plugin that is designed to only appear on mobile devices. However, I am encountering an issue where the page content overlaps the footer on phones. I attemp ...

Display a pop-up window using window.open and automatically print its contents using window.print upon loading

I am trying to open a new window with some HTML content and then automatically print it. Here is the code snippet I have: var windowObject = window.open('','windowObject','arguments...'); windowObject.document.write("<html ...

I'm having trouble getting $(this) to save in local storage. I want to add a class to $(this) and have it still there even after a

$("ul").on("click" , "li.afterdone" , function(event){ $(this).toggleClass("done") }); Here is the code snippet I've been working on: I am trying to figure out how to make the 'done' class persist on a specific li.afterdone element e ...

What steps can I take to address security issues related to iframes?

Are there other security risks to consider when using iframes besides XSS vulnerabilities? How can I ensure that my website is secure when utilizing iframes? I've seen some JavaScript code that uses top.window, but I'm hesitant to rely on client ...

Enabling Night Mode in an AngularJS Application

Currently, I am working on adapting an AngularJS project to support Dark Mode. This application is a legacy system and quite intricate so I prefer not to duplicate the css file. At present, the implementation involves monitoring a media query from the op ...

HTML file unable to connect with CSS stylesheet

I'm facing an issue where my CSS stylesheet and HTML files aren't linking properly. Here is the code snippet from my HTML file: <head> <title>Website Sample</title> <meta charset="UTF-8"> <meta http-equiv= ...

Troubleshooting issue: Utilizing $(this) with Vue.js in jQuery method is not functioning as

Initially, I understand that combining jQuery with Vue is not advisable. Nevertheless, I am attempting to modify an element after a click event but encountering issues with $(this). methods: { openSMS() { $(this).hide(); // <-- facing difficulty ...