What is the best way to update auto margins after resizing an element with Javascript?

I'm having an issue with a DIV on my webpage that is centered using margin-left and margin-right set to auto. When I try to resize the DIV, it no longer stays centered on the screen.

<div id="content" style="margin-left:auto;margin-right:auto;width:240px">
  <p>Lots of text</p>
</div>

Elsewhere in the code:

$("#content").width(480);

After resizing, the div becomes unbalanced either to the right or left. How can I make sure that the margins adjust accordingly when the width changes, while still maintaining center alignment? This needs to work across all modern browsers.

Answer №1

The div is still centered, but the text inside it is now aligned to the left.

Here's an example of how you can achieve this:

<div id="content" style="margin-left:auto;margin-right:auto;width:240px;border:1px solid red;text-align:center">
  <p>Click here</p>

$('p').click(function(){$("#content").width(480)})

- http://jsfiddle.net/nvzaw/1/

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

Retrieve data points from ol.layer.Vector using OpenLayers 4

Having recently started using OpenLayers, I find myself in a state of confusion. I'm attempting to retrieve all features from a kml vector layer, but have been unsuccessful thus far. It perplexes me as to what mistake I might be making. Below is the ...

Stylish CSS for your website's navigation

I am facing a challenge with creating a menu for my website. I want it to be positioned on the left side, similar to the image provided below. However, despite writing the code and applying styles as expected, the menu does not display correctly and appear ...

Is it possible for JQuery to interact with an Access database for both reading and writing

Is it possible to utilize Jquery to establish a link with a Microsoft Access database? I have been exploring this possibility but haven't found any relevant information. This database won't be used for a production site, but rather for a small gr ...

When I try to insert new data into a MongoDB collection during an update operation, the existing data is being overwritten instead

While updating data, I have a requirement to also add new data. Specifically, I need to append data to an existing object in a for loop that stores data in a database. However, when attempting this, the data is being updated instead of added to the current ...

How can we fetch data from the server in Vue 2.0 before the component is actually mounted?

Can anyone help me with this question noted in the title? How can I prevent a component from mounting in <router-view> until it receives data from the server, or how can I fetch the data before the component is mounted in <router-view>? Here a ...

What is the process of importing schema and resolvers in GraphQL-Yoga or Node?

After discovering that graphql-yoga V1 is no longer supported, I'm aiming to upgrade to graphql-yoga/node V2. Although I've reviewed the official documentation on the website, I'm encountering difficulties in migrating from V1 to V2. Is it ...

After the entire webpage has loaded, the jQuery AJAX method encounters a failure when attempting to update the

I am relatively new to using jQuery AJAX, so please be patient as I try to explain my situation. I am working on implementing a like button for my website that functions similarly to the Facebook like button. To enable users to click on the like button, th ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

What is the best way to modify JSON data within a file?

To start, I retrieve a JSON array by using the following JavaScript code: $.getJSON("myJSONfile.json") .done(function(data) { myData = data; }); After storing the data in myData, which is a global variable, I proceed to add more informati ...

Is there a problem with the timing of jQuery rollover/out button functionality?

I have a setup in progress where a series of buttons with titles reveal more information on rollover. The layout features an intro section in the center, surrounded by the buttons. When hovering over any button, it triggers a function to hide the intro and ...

Issue encountered: ENOENT error - The specified file or directory does not exist. This error occurred while attempting to access a directory using the

I don't have much experience with nodejs or express, but I have an API running on http://localhost:3000. One of the endpoints triggers a function that uses the file system to read a file synchronously. However, when I send a post request using Postman ...

CSS: generating space between lines within a single paragraph

I need help styling a multiline paragraph with varying width. I want each line to have a solid background color, except for in between two lines where I want to display a background image. For example, visit I've attempted adjusting the line-height, ...

Webpack Encore: SCSS import order causing unexpected issues

When developing with Symfony + Webpack Encore, I aim to split styles into "layout" and "page-based" categories for convenience. However, despite this organization, I still prefer to compile all styles into a single CSS file. To achieve this, I structure my ...

Update the referenced lists in ng-admin

I'm currently working with ng-admin alongside a restful API, I have various referenced lists that undergo frequent updates from the server side. Is there a method to automatically refresh these referenced lists every 5 seconds using ng-admin? EDIT: ...

Issue with Redirecting in React: REST requests are not successful

There's a text input that triggers a submission when the [Enter Key] is pressed. const [ query, setQuery ] = React.useState('') ... <TextField label="Search Codebase" id="queryField" onChange={ event => setQuery( ...

Issue with returning value from promise object in Next.js

Hello! I am fairly new to JS and React, so I would appreciate your patience as I try to navigate through this. It has been quite a journey so far. In my component, I am fetching JSON data from a URL and attempting to extract a specific value from it to d ...

Converting Laravel variable into an image using JavaScript

I have a base64 string that I'm passing from the controller to the view. After verifying that the base64 string is correct online (by converting it to an image), I am attempting to call it in my JavaScript like so: <script> var crosshairImg ...

It is not feasible to establish a personalized encoding while sending a post request through XMLHTTPRequest

When using the JS console in the latest version of Chrome browser, I encountered the following issue: x = new XMLHttpRequest(); x.open('POST', '?a=2'); x.setRequestHeader('Content-Type', 'application/ ...

Executing an automated process of adding items to the shopping cart using Python without the need to have a

Does anyone know of a way to automate the add-to-cart process using Python without the need for an open browser window? I've experimented with modules like mechanize, but they lack the ability to directly interact with web elements. Currently, I&apo ...

Alternate Row Colors Using Odd/Even CSS Styling for Main Headings

In my expand/collapse table, I have set up alternating row colors (dark grey and light grey) that adjust automatically when expanding or collapsing. The challenge I'm facing is that for certain rows, I want to apply a specific background color using ...