Ensure that the main div remains centered on the page even when the window size is adjusted

Here is the code snippet:

<div id="root">
<div id="child1">xxxx</div>
<div id="child2">yyyy</div>
</div>

CSS :

#root{
    width: 86%;
    margin: 0 auto;
}
#root div {
    width: 50%;
    float: left;
    border: 1px solid red;
}

This code centers the "root" div to the page, but there are alignment issues on certain resolutions.

To address this without using media queries due to compatibility with IE8, below is some JavaScript/jQuery code:

<script type"text/javascript">
if (window.screen.availWidth >= 1200 && window.screen.availWidth <= 1390) { 
    $("#root").css("width", "92%");
} else {
    $("#root").css("width", "86%");
}
</script>

However, the div content misaligns when the browser window is resized. The challenge is how to keep the div centered for all resolutions and window sizes.

If you're unsure about setting the width percentage dynamically for each window resize, a solution could involve calculating the center based on the viewport size changes. This approach can help maintain alignment regardless of the screen resolution or resizing.

Feel free to experiment with responsive design techniques or seek further guidance on resolving this issue effectively.

Best regards,

Answer №1

There is no need to rely on any script to center content, as it can be achieved through CSS:

You can view a working example in this DEMO

Answer №2

Consider incorporating it into the .resize() method:

$(window).on('resize', function(){
   if ($(this).width() >= 1200 && $(this).width() <= 1390  ) { 
      $("#root").css("width","92%");
   }else{
      $("#root").css("width","86%");
   }
}).resize();

There might be an issue here:

#root
{
    width:86%  // You seem to be missing a ';' here.
    margin:0 auto;
}

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

How to make a GET request to a Node server using Angular

I am currently running a node server on port 8000 app.get('/historical/:days' ,(req,res,next){..}) My question is how to send a request from an Angular app (running on port 4200) in the browser to this node server. Below is my attempt: makeReq ...

What methods does Angular use to display custom HTML tags in IE9/10 without causing any issues for the browser?

Exploring web components and utilizing customElements.define tends to cause issues in IE9/10. I've noticed that Angular is compatible with IE9/10, and upon inspecting the DOM tree, it seems like Angular successfully displays the custom element tags. ...

Is the Vis.js network function ready to go?

Utilizing the Vis.js network library to display graphs and am curious if there is a dedicated finishedLoading event available for this object? Any suggestions or insights are appreciated! ...

Creating HTML content in TypeScript with NativeScript using document.write()

Essentially, I am looking to create a set number of labels at various row and column positions depending on the user's input. However, I have been unable to find any resources that explain how to write to the .component.html file from the .component.t ...

Exploring Virtual Reality with the Oculus Quest2 and Three.js

Currently, I am working on a project using Oculus and three.js to create a virtual reality experience. To test the functionality, I decided to try out the official sample provided. Here is the link to the official sample. My intention was to access the s ...

Tips for retrieving and transforming the date time picker into the server format (toISOString)

I am attempting to utilize a datetime picker and convert it for server-side transmission, but I'm encountering issues. Here is my attempted code: <html> <head> <meta charset="utf-8"> <meta name="viewport" cont ...

Customize the appearance of Angular components by altering their color schemes

When working on my project, I often utilize pre-made Angular components. However, some of these components come with colors that do not align with the overall aesthetic of my project (refer to image above). To rectify this issue, I am looking to replace t ...

The XPath for the element that comes before a specific text

Looking for the XPath of the following code snippet: <a class="account-name" long-text="Sample Text" ng-click="accountClick(account)" ng-href="sample URL" href="sample URL1"> <span>Plan Name</span></a> I attempted this: //span[te ...

Utilizing Chart.js to visualize live data from a dynamic MySQL dataset

Struggling to create a dynamic dataset for my Chart.js project, specifically with the data obtained from getpromorevenuechart.php. Here's an example of the dataset: [{"mmyy":"2019-12","promocode":"promo1","amount":"2776"},{"mmyy":"2020-01","promocode ...

Executing click function immediately upon loading the page

Could someone explain to me why this click function is triggering on page load? I am coding in WordPress. jQuery(document).ready(function($){ $('.scroll_Top').click(function(e){ console.log("Hello"); }); }); ...

What is the technique to achieve a seamless blur effect?

Is there a way to create a smooth blur similar to a gradient transitioning from transparent to dark? .img { background: url(https://4kwallpapers.com/images/walls/thumbs_2t/13551.jpg); background-size: cover; background-position: center; width: 5 ...

Display or conceal a YouTube video with a click

Q1) Is it possible to use JQuery on page load to detect the file name of an image and then dynamically position it on the page with CSS? Q2) What is the most efficient way to achieve this without embedding iframe code inside a specific div.icon element? ...

Stacked list using IE7 browser compatibility

Currently, I am facing an issue with IE7 where the list appears at the top of the submenu. Is there any solution to bring it back to its intended position? Surprisingly, this problem does not occur in IE8 or higher versions. I would greatly appreciate it i ...

Guide on effectively sorting the second level ng-repeat data in a table

I have a collection of data objects that I want to present in a tabular format with filtering capabilities. The current filter, based on the 'name' model, successfully filters the nested object 'family'. However, it does not function as ...

Every time I attempt to log into my app, I encounter a persistent 401 error message

I've implemented a user/login route that retrieves a user, compares their password with a hashed version, creates a token, and sends it to the front end. However, I encountered a persistent 401 error in the console on the front end, leading to the fin ...

What are the best practices for utilizing CSS position (relative, absolute) combined with percentage dimensions for height and width?

There are numerous questions and answers related to this topic, but I have not come across a case like the one mentioned below. Everyone talks about setting the height and width in percentage by first setting the parent's height in percentage, but it ...

Is it possible to share deep links with just a hashtag?

I am currently developing a web application and I want to include social media buttons such as Facebook Like. I have tried using the HTML code/API provided by Facebook, AddThis, Shareaholic, ShareThis, but none of them seem to properly handle my deep link ...

Utilizing the nativescript-loading-indicator in a Vue Native application: Step-by-step guide

I am attempting to incorporate the nstudio/nativescript-loading-indicator package into my Vue Native App, but I am experiencing issues with its functionality. import {LoadingIndicator, Mode, OptionsCommon} from '@nstudio/nativescript-loading-indicato ...

Launching a call to action through Ajax in Zend Framework triggers a redirect, but subsequent calls prove to be effective

I've encountered an intriguing issue that I'm hoping someone else has come across and resolved before. In this particular application, I have implemented a 'change my password' option for users. If a user forgets their password, they c ...

Exploring jQuery: Implementing a SlideDown Effect on Loading Questions

Greetings, this is my debut post on stackoverflow. I have been an avid reader and learner here. I am currently using a jQuery function to load posts in WordPress themes using the .load function. However, I am facing a challenge that I cannot resolve on m ...