In the context of resizing elements within a scrolled div, CSS divs with margin auto may not always be perfectly centered

I am encountering an issue with centering divs within another div with overflow:auto; initially, all divs are centered using margin: 0 auto; however, when I use jQuery to resize the last div, a scrollbar appears (as expected) but the other divs remain in their original positions. I want all the divs to automatically realign themselves at the center of the scrolled div.

Here is how I resize the last div:

$('#boton').click(function(){
    $('.div2').css({width:'400px'});
});

You can see it in action in this fiddle, just press the "resize" button:

http://jsfiddle.net/odabart/cAyVF/1/

EDIT:

Since I do not know which divs will be resized in advance, I am looking for a solution that uses only CSS for automation purposes; jQuery is used here solely for demonstration.

Answer №1

To effectively enhance the layout, it is necessary to introduce a wrapping div around all instances of div1 and div2, adjusting the dimensions of this wrapper accordingly. The revised HTML structure will appear as follows:

<div style='overflow:auto;width:200px;height:300px'>
    <div class="wrapper">
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div2"></div>
    </div>
</div>
<input type='button' id='boton' value="resize"/>

Add the following line in the JavaScript section to handle resizing when the button is clicked:

$('#boton').click(function(){
    $('.div2, .wrapper').css({width:'400px'});
});

Sincerely,

Answer №2

All of the yellow div elements are currently being centered within a parent element with a width of 200px. To center all the divs, an additional div needs to be added and resized using jQuery.

Check out the demonstration here: http://example.com/demo

HTML:

<div style='overflow:auto;width:200px;height:300px'>
    <div class="inner">
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div2"></div>
    </div>
</div>
<input type='button' id='btnClick' value="resize"/>

jQuery:

$('#btnClick').click(function(){
    $('.div2').css({width:'400px'}).parent().css({width:'400px'});
});

Answer №3

If you're looking to automatically center the yellow divs in relation to the blue div, one approach is to use jQuery to adjust the width of the containing div and have the blue div expand accordingly.

UPDATED AS PER SPECIFICATIONS

View Updated JSFiddle example

jQuery

$('#boton').click(function(){
    $('.wrapper').css({width:'400px'});
});

HTML

<div class="frame">
    <div class="wrapper">
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div1"></div>
        <div class="div2"></div>
    </div>
</div>
<input type='button' id='boton' value="resize"/>

CSS

.frame {
    overflow: auto;
    height: 300px;
    width: 200px;
}

.wrapper { width: 200px; }

.div1{
    width:100px;
    height:50px;
    background-color:yellow;
    margin: 0 auto;
    border:1px solid black;
    display:block;
}

.div2{
    width:100%;
    height:50px;
    background-color:blue;
    margin: auto;
    left: 0;
    position: relative;
    right: 0;
}

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

Placement of the Zend submit button

How can I position the submit button at the bottom of a form wrapped in an HTML table, when calling two forms from the same controller? Currently, the button is stuck between the first form and the table. I attempted to assign the element in my controller ...

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...

Steps to launching a URL in a new window on Internet Explorer

I want it so that when button1 is clicked, the URL opens in a new window using Internet Explorer. ...

Retrieve the browser version of a client using C# (When Internet Explorer Compatibility mode is activated)

Is there a way to retrieve the actual version of the client's browser from C# code? Using Request.Browser or HTTP_USER_AGENT provides details, but in Internet Explorer (IE), when compatibility mode is enabled, it always returns IE 7 regardless of the ...

Is it possible to apply an onclick event to list items using Ajax and jQuery?

This particular code block functions correctly: $(document).ready(function () { $.getJSON('./record.json', function (data) { var studentsHTML = '<ul>'; $.each(data, function (index, student) { stude ...

What is the best way to find elements in a jquery array that match any part of the text within a div?

I'm almost there in getting this to work. I just need to figure out how to check if a specific item from an array is present in the text inside div containers with a particular class. This is what I attempted to do using the indexOf method to search ...

What could be causing the malfunction of the Carousel Slide feature in my code?

I have encountered an issue while trying to implement the Bootstrap code below. It seems to only display the first slide and does not progress to the next one. I am unsure of what might be causing this problem. Can anyone help me troubleshoot? <secti ...

What is the best way to link an anchor tag to a specific tab's content section

*Attempting to understand how to implement an anchor tag that will open a specific tab* *JavaScript code for navigation tabs* function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent" ...

There seems to be a lack of information appearing on the table

I decided to challenge myself by creating a simple test project to dive into Angular concepts such as CRUD functions, utilizing ngFor, and understanding HttpClient methods (specifically get and post). After creating a Firebase database with an API key and ...

How do you eliminate row highlighting on the <TableRow> component within Material-UI's <Table> using ReactJS?

I am facing an issue with a table and row highlighting in my code. Even after clicking on a row, it remains highlighted. I attempted to use the <TableRow disableTouchRipple={true}> but it didn't work as expected. What can I do to remove the high ...

Use the ng-repeat directive to display multiple items and let the user input a quantity for each item. Then, in AngularJs, gather all the form data, including the repeated items and their quantities, and

Hey there! I have a question related to AngularJs: How can I repeat pre-selected items using (ng-repeat) and allow users to enter a quantity for each item in a subsequent step, then submit all the form data? I'm wondering if adding $index to the repe ...

Form alignment issue: Bootstrap justify-content feature not functioning as expected

I am having trouble aligning my input form that is designed to capture Twitter handles in the center of the page. Despite using Bootstrap and ASP.NET, I cannot seem to get it to work as intended. Here is a snippet of the relevant CSS/HTML code: <form ...

Expanding the size of your Bootstrap 3 input box

https://i.sstatic.net/h7HpX.png Incorporating Bootstrap 3 into a Flask application, I have created a basic layout so far: <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="content"> ...

Can a webpage be redirected to another page while passing along the id from the original page?

https://i.sstatic.net/3LhYJ.png I have a page that displays shop names and addresses along with an edit function in views.py: def update_shop(request, id): context = {} # * fetch the object related to passed id obj_shop = get_object_or_404(VideoL ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...

Animating content through CSS and jQuery to reveal its unfolding effect

Just stumbled upon the amazing quote-expansion animation in the OSX Mail app and I am completely impressed. I am on a mission to bring that same magic to the web (or at least close to it), but unsure if anyone has done something similar yet. A couple of ...

Guidelines for sending a personalized email through the WordPress admin dashboard

Currently, I am working on modifying a small plugin that calculates the deposit amount for an item. After the user pays the deposit, the plugin automatically sends an email to notify them about the successful payment. My goal is to enhance the functionali ...

What is the best way to send an image object in a Django HTTP response?

When sending emails with images, I utilize html templates. My goal is to have the images generated dynamically upon opening the email. Therefore, the 'src' attribute in the image tag calls a REST api within my app to create the image on-the-fly. ...

Submitting an HTML form to a PHP file for processing before returning to the original HTML page for further interaction

I am looking to figure out how I can send a <FORM> from an HTML page to a PHP file that will retrieve data from a database and then return the results to the same HTML page without any redirection. What I aim for is to avoid redirecting users. Take ...

CSS border-image negative positioning (no HTML required)

We are on the lookout for a way to apply a specific border style to nearly all img tags within the content area of a CMS (such as Wordpress or Joomla). Our goal is to achieve this solely using CSS without having to access any parent tags: The initial step ...