Adjusting the position of a nested element as the width of its parent container

It's a bit tricky to explain, but essentially I have two divs and when I click the button, instead of moving the elements, I want to change the width of their parent containers to prevent any overlapping.

Interestingly, the one on the right edge of the screen behaves as expected, giving the illusion that the inside element is going out of the screen.

The same effect doesn't work on the left side. Even when I tested changing the inner element to absolute positioning.

In simple terms, when I click Run, I expect the text on the left side to be gradually pushed off the screen as the parent container's width decreases.

This is what I am aiming for:

$("#run").on("click", function() {
  $("#cont-left, #cont-right").toggleClass("hide");
});
#cont-right {
  position: absolute;
  top: 0px;
  right: 0px;
  width: 200px;
  overflow: hidden;
  border: 2px solid blue;
  transition: all 0.5s ease-in-out;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  -o-transition: all 0.5s ease-in-out;
}

#test {
  background: yellow;
  left: 0px;
}

#cont-left {
  position: absolute;
  top: 0px;
  height: 30px;
  left: 0px;
  width: 200px;
  overflow: hidden;
  border: 2px solid green;
  transition: all 0.5s ease-in-out;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  -o-transition: all 0.5s ease-in-out;
}

#test2 {
  background: pink;
  right: 0px;
}

#run {
  display: block;
  width: 100px;
  background: red;
  cursor: pointer;
  margin: 0 auto;
  color: white;
  padding: 10px 0px;
  text-align: center;
  font-weight: bold;
}

#run:hover {
  background: green;
}

#cont-right.hide,
#cont-left.hide {
  width: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cont-right" class="hide">
  <div id="test">
    111<br />222<br />333
  </div>
</div>

<div id="cont-left" class="hide">
  <div id="test2">
    111<br/>222<br />333
  </div>
</div>
<span id="run">Run</span>

Answer №1

If your content is purely text, consider using text-align

If you are dealing with text only, a simple CSS adjustment can solve the issue:

#cont-left {
  text-align: right;
}

If it's more than just text: utilize flex

If you have elements other than text, implement display: flex; to enable justify-content: flex-end; (aligning the content to the end). These properties should be applied to both containers #cont-left and #cont-right. For #cont-right, use justify-content: flex-start;

Note that applying these values will affect the width of divs #test and #test2, requiring you to adjust the background-color on parent divs or set width: 100%;

The code snippet below has been updated to include the necessary flex changes.

$("#run").on("click", function() {
  $("#cont-left, #cont-right").toggleClass("hide");
});
#cont-right {
  position: absolute;
  top: 0px;
  right: 0px;
  width: 200px;
  overflow: hidden;
  transition: all 0.5s ease-in-out;
  display: flex;
  justify-content: flex-start;
  background: yellow;
}

#cont-left {
  position: absolute;
  top: 0px;
  height: 30px;
  left: 0px;
  width: 200px;
  overflow: hidden;
  transition: all 0.5s ease-in-out;
  display: flex;
  justify-content: flex-end;
  background: pink;
}

#run {
  display: block;
  width: 100px;
  background: red;
  cursor: pointer;
  margin: 0 auto;
  color: white;
  padding: 10px 0px;
  text-align: center;
  font-weight: bold;
}

#run:hover {
  background: green;
}

#cont-right.hide,
#cont-left.hide {
  width: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="cont-right" class="hide">
  <div id="test">
    111<br />222<br />333
  </div>
</div>

<div id="cont-left" class="hide">
  <div id="test2">
    111<br/>222<br />333
  </div>
</div>
<span id="run">Run</span>

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

Tips for converting server dates into a readable format in JavaScript

I have been struggling with a seemingly simple problem for quite some time now. I am working with angular.js and specifically using the input type 'time'. The issue arises when the server returns a date in the following format: shiftStarted = " ...

Having difficulty automatically adjusting the width of HTML columns according to their content

I have a HTML table that I want to automatically set the width of the table columns, adjusting based on the content within. Despite setting the width to auto, as shown in the image below, the content in the ID column does not stay confined to a single line ...

Function compilation did not succeed in the module

I've put together a MERN (MongoDB, ExpressJS, React, Node) project using express-generator (express myNewApp). Within a react component, I have implemented this ES6 code snippet: onChange = (event, { newValue }) => { // Line 53 this.setSt ...

A guide on invoking an onclick function within a Template literal in React.js

I am seeking assistance with implementing an on-click function using template literals in React JS. When a button within the template literal is clicked, I want to trigger another function in React JS. addPopupToLayer = (surface, layer) => { cons ...

What is the best way to implement a live filtering mechanism in JavaScript or React for a website?

Trying to implement a filter for an array of items where the list displayed will change based on user checkbox selection. Multiple selections should apply ANY (not ALL) conditions to the filter. The current code only filters based on the first checkbox se ...

Transforming a JavaScript array into a JSON format

Is there a way to convert a JavaScript array into JSON format? [{ "userName": "Rodrigo", "date": "April 25, 2017", "score": 5 }] [{ "userName": "Jon", "date": "April 24, 2016", "score": 4 }] Error: There is a parser error on line ...

What is the best way to store data retrieved using a model.find({}) operation?

I am currently attempting to calculate the average value of a collection in my database using Mongoose and Express. The objective is to utilize this calculated value on the "calculator" page when rendering, which is why it is embedded in a post for that sp ...

Protractor experiencing difficulty in adjusting price slider

As a newcomer to protractor, I am attempting to test a price slider that sorts products based on the provided price range. Unfortunately, I am facing difficulty in dragging the slider (min point) using protractor. Can anyone provide guidance on how to move ...

Retrieve the success return value from Iron-Ajax following a POST request

Currently, I am working on a project using Polymer and I am interested in retrieving the response value from an API after making a POST request with Iron-Ajax. Below is a snippet of my code: var response = $.ajax({ type: "POST", url: apiUrl, ...

Textarea caret doesn't move to next line on enter key press (specifically in Chrome)

<textarea cols="152" rows="5"> Press the space key repeatedly after the end of this sentence and you'll see that the cursor won't move to a new line but will stay in place. Go ahead, start pressing the space key now </textarea> When ...

Encountering a problem when attempting to send a JSON object with the BeanShell PreProcessor

I need to send a JSON Object to the HTTP Request body in JMeter using the BeanShell PreProcessor. The JSON object is modeled using java code with some business logic. I have created a BeanShell PreProcessor and written the java code below, import org.json ...

Send the image data using ajax with jQuery

I had an idea to create a user interface where the user can choose how many forms to create, select the form to edit, specify the number and type of elements for each form. Here's what I've done so far: <h2>Questions</h2><br> ...

The navigation bar on the web app is functioning properly on Android devices but experiencing a CSS problem on

My Nextjs web app includes a navbar with a hamburger menu, logo, and avatar. The navbar functions perfectly on desktop in Chrome, Mozilla, Brave (in developer tools mobile mode), and on Android phones using Chrome. However, when accessed from an iPhone X, ...

Automatic padding within Bootstrap5

I'm struggling to understand why I am experiencing a consistent padding at the bottom of my container in Bootstrap5. I attempted to use align-items-center within the row to center the content, but it had no effect. <!DOCTYPE html> <html la ...

What methods are available to create a transition animation for an HTML 5 banner on iOS devices?

I need assistance with animating an HTML5 banner to transition vertically onto the screen in my app demo. After a prompt that triggers a server callback, the banner should smoothly move down from the top of the screen. The animation I am aiming for is simi ...

Navigating through parent folder HTML files from child folder HTML files

Seeking guidance as I embark on a new project! Check out this link to see my skills in action: collegewebsite.zip Now for the query at hand. I am working on a project named Coffee Cafe for my tuition assignment. It involves utilizing CSS and HTML with J ...

Responsive card design created by Bootstrap element

Hello lovely people, I'm currently facing an issue with two triangles that are supposed to be next to each other with a small gap in between. However, when I resize the screen, they start moving freely and don't stay within the designated card ar ...

Is it possible to maintain the scroll position of a PrimeNG table when updating the data?

I've encountered a challenge while working on a project involving PrimeNG 12 tables with Angular 12. The issue lies in Angular's change detection mechanism and updating table data, specifically in preventing a PrimeNG p-table from scrolling back ...

JQuery function within the "onclick" event

$('.more').click(function showFriendInfo(id) { $('#MoreFriendInfo'+id).toggle(); }); I created this function called showFriendInfo(id), but how can I properly link it in HTML/PHP to obtain the id? I attempted the following ...

How can I integrate checkboxes in a list view with jQuery Mobile?

How can I display the status of users with three different levels in a list view? I need to show whether they are attending or not, similar to the image provided. The issue is that currently the checkbox appears below the name, but I want it to be at the r ...