The dimensions of a div are constantly fluctuating

I need to adjust the width of .center. There are multiple rows, some with a button and others without. Since it loads dynamically, the width of .center should vary for each row.

For instance, in the first row, .center should have a width of centerWidth2
In the second row, .center should have a width of centerWidth1

This is the desired layout, but the challenge is that I don't always know when .right is visible or not. Therefore, I want .center to automatically adjust its width based on the visibility of .right.

var centerWidth1 =  $('#wrap').width();
var centerWidth2 =  $('#wrap').width()-55;

$("#first").css('width', centerWidth2);
$("#second").css('width', centerWidth1);
#wrap {
position: relative;
margin: 20px auto;
width: 80%;
background-color: red;
}

.row {
position: relative;
height: 30px;
margin-bottom: 10px;
}

.center {
float:left;
min-height: 30px; line-height: 30px;
display: inline-block;
text-align: center;
background-color: blue;
}

.right {
float:left;
width: 50px; height: 30px; line-height: 30px;
display: inline-block;
text-align: center;
margin-left: 5px;
border:0;
background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="wrap">
<div class="row">
<div class="center" id="first">center</div>
<div class="right">right</div>
</div>
<div class="row">
<div class="center" id="second">center</div>
</div>
</div>

Answer №1

To achieve the desired outcome, I utilized the .each() method to iterate through the rows. Within each .row, I checked for the existence of the .right element using right.length > 0. If present, I calculated the difference between the width of the .right element and the width of #wrap, then applied this value to .center. In cases where .right was not found within the row, I simply used the width of #wrap.

Additionally, I accounted for the margin-left:5px; on .right by retrieving the margin left value using

right.css('marginLeft').replace('px', '')
and subtracting it from the total width.

If possible, I suggest utilizing flexbox for a more straightforward solution. (Refer to the example following the one below)

Recommended Flex Solution

This alternative approach offers a simpler solution with reduced processing requirements.

/* FLEX CSS START */
.row {
  display:flex;
}
.center {
  flex-grow:1;
}
.right {
  flex-shrink:1;
}
/* FLEX CSS END */
#wrap {
  margin: 20px auto;
  width: 80%;
  background-color: red;
}

.row {
  height: 30px;
  margin-bottom: 10px;
}

.center {
  min-height: 30px; 
  line-height: 30px;
  text-align: center;
  background-color: blue;
}

.right {
  width: 50px; 
  height: 30px; 
  line-height: 30px;
  text-align: center;
  margin-left: 5px;
  background-color: grey;
}
<div id="wrap">
<div class="row">
<div class="center" id="first">center</div>
<div class="right">right</div>
</div>
<div class="row">
<div class="center" id="second">center</div>
</div>
</div>

Answer №2

Assuming there may be uncertainty about the presence of a .right element, it is wise to plan for its appearance or disappearance based on user interactions within rows. Consider keeping the element in the document but toggling its visibility using CSS properties like display: none. This approach allows for seamless control over the element without affecting the layout flow. Avoid using other visibility options like visibility: hidden or opacity: 0.0 as they still occupy space and affect visibility status differently.

For example, demonstrate different statuses of the .right element in four rows to visualize the outcome:

<!DOCTYPE html>
<html>
    <head>
        <title>Dynamic center</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
    </head>
    <body>
        <div id="wrap">
            ... (HTML code with row examples)
        </div>
    </body>
</html>

The script provided iterates through rows to adjust the width of the "center" elements based on the visibility of the associated "right" elements. By targeting each element individually, you can ensure precise adjustments are made according to your requirements.

$(function() {
    var rowCount = $(".row").length;

    // Adjust center width based on right element visibility
    for (let i = 0; i <= rowCount; i++) {
        if ($(".row").eq(i).children().eq(1).is(":visible")) {
            // Set custom widths for center element as needed
            $(".row").eq(i).children().eq(0).width(centerWidth2);
        } else {
            $(".row").eq(i).children().eq(0).width(centerWidth1);
        }
    }
});

Ensure proper CSS styling by setting box-sizing: border-box, avoiding unnecessary attributes like inline-block, to enhance interface consistency. Consider utilizing flex display properties for improved alignment flexibility in responsive layouts.

Test the provided solution and make adjustments accordingly for optimal performance.

EDIT - Using Flexbox:

(Include CSS styles and HTML structure that leverage flexbox for enhanced layout control)

This implementation accommodates dynamic changes in element visibility seamlessly while maintaining layout integrity. Run the code snippet to see the functionality in action.

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 displaying data by using the append() function when the page is scrolled to the bottom

How can I use the append() function to display data when scrolling to the bottom of the page? Initially, when you load the page index.php, it will display 88888 and more br tags When you scroll to the bottom of the page, I want to show 88888 and more br ...

Looping through an array of objects in VueJS can become a bit tricky when dealing with objects whose properties are dynamic. How can I efficiently

I am looking to create a matrix display from an array of objects, but the properties of the objects may change over time. Here is an example of the data: [ { location: "Japan", webhookStatus: "Up", authenticationStatus: &q ...

Issue with Mobile NavBar remaining visible after clicking on target element in HTML CSS

On my website, everything works perfectly with the Nav bar except for when I am on mobile. When I click on any href from my Nav Bar, it directs me to the correct location but does not close the Nav Bar afterward. I need it to function this way: After click ...

What causes the default date to be displayed on the datePicker in MVC when using Persian dates?

Trying to pass the value of a datePicker input to the action via model always results in receiving the following value: Date = {1/1/0001 12:00:00 AM} Ajax is used to serialize and send the values of inputs to the action. Upon inspection in the console, i ...

Attempting to disrupt the PHP script responsible for handling the form data sent via the $_POST method

I have been searching for specific information on this issue. My HTML5 form... outputs to an external PHP script saves the form data as $_SESSION variables in PHP transfers the variables to another page for display I haven't yet escaped any of the ...

Conceal the scrollbar and enable horizontal swiping using CSS

I have set up a container where I want the content to scroll horizontally from left to right on mobile devices, and I would like to be able to swipe to navigate while hiding the scrollbar. You can view the implementation on this JSfiddle link Do you think ...

Tips for accessing elements in CSS

I can't seem to find a specific question that matches mine exactly, but I need assistance in extracting an element from the DOM using CSS to apply a style to it. The block structure is similar to this: <div class="parent-block"> &l ...

Fetch the contents of a div from a PHP page on a different domain and display it on another webpage

Hey there, I hope you're having a great morning! I'm currently working on setting up an affiliate box for our affiliates within Wordpress. I've managed to create it dynamically and you can check out an example here The values needed to cre ...

Navigate across list items using the tab key in Angular 7

Below is the sidenav menu snippet containing various items: <ul class="account-settings-container" *ngIf="isUserActive"> <li> <app-account-information></app-account-information> </li> <li> <app-theme-p ...

The function is missing from the object, leading to a script error with jQuery

When using different versions of jQuery, I encountered some issues with saving changes in my application. Initially, with jquery-1.4.4.min.js, everything worked except for the save function due to an error I made. However, when switching to jquery-1.7.1.mi ...

Tips for Utilizing the Accurate Google Map Code within Jquery Tabs

Looking for assistance in properly integrating Google maps into jQuery tabs. I am trying to incorporate two maps into the project. One map to display the location and another map to provide directions. Encountering an issue with the code, as Firebug rep ...

transferring data between pages without the need for a form tag

<a href='new.php?logi_jo=$_POST[jo]'>submit</a> <input type='text' style='width:50px' name='logi_jo'> Is there a method to extract the value of logi_jo and transfer it to another webpage without u ...

Dealing with distinct values in structured data input

Greetings to everyone. Situation Overview In my project, I have a model called resumeSkills which stores the resume ID, skill ID from different tables, and a field for "proficiency level" to indicate the expertise level in that specific skill. https://i ...

Execute a newline command and retrieve data from choices in a PHP script

I have been struggling with writing to a text file using PHP. There are two issues that I cannot seem to resolve. The first problem is that I am unable to create a new line, despite trying multiple methods. The second issue is related to reading the value ...

Duplicate data insertion issue encountered when choosing from table utilizing checkbox

I'm having issues with the loop in this code. Whenever I select data from a table using checkboxes (which is generated using JSON), the selected data gets added multiple times. What could be causing the problem in this code snippet that loops through ...

Guidelines for creating a basic CSS modal

I am working on creating simple modal divs: <div class="modal"></div> <div class="modal-content"></div> Here are the related CSS rules: .modal{position:fixed;background:#444;opacity:0.5;width:100%;height:100%;left:0;right:0;botto ...

Disable the click event using jQuery

$("button").click(function (){ $("<button>Start</button>).appendTo('main'); }); The code above introduces a functionality where clicking a button generates another button dynamically. However, each subsequent click kee ...

Using CSS to align the position of a div with the last word position of an h4 element

Trying to figure out how to position a div at the end of an h4 text element has been challenging. When the h4 text is on a single line, it's easy to place the div correctly. However, things get complicated when the text spans multiple lines. In that c ...

Nested for loops are utilized in order to extract names from a JSON array

I am faced with a challenge involving a container that contains rows with 4 columns each. My goal is to retrieve the title of each column using ajax from a json array by utilizing a for loop. Initially, I successfully achieved this for one row using a sing ...

How to create a heading within a Bootstrap list item?

Attempting to replicate this layout using Bootstrap 3 This is my current progress <ul class="list-group"> <li class="list-group-item> Cras justo odio </li> <li class="list-group-item> Dapibus ac facilisis in </l ...