What is the best way to use jQuery to center a div in the middle of a webpage and ensure it remains centered even when the window is resized?

Is there a jQuery script available that can keep a div centered in the middle of the window and adjust its position when the window is resized? I am working on a lightbox plugin and it's crucial for the div to stay centered. CSS hasn't been effective in achieving this so far.

Additionally, I need the div to remain centered even when another box with larger dimensions is opened. You can see examples on this page: . When you open an image first, followed by the div, you'll notice that the div isn't centered initially. However, it gets centered when closed and reopened due to the .center() function triggered by clicking on a WowBox link. My goal is to ensure that it always stays centered without any issues.

The code snippet I'm currently using to center the div is as follows:


jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

I aim to implement a solution where the div remains centered upon window resizing and adapts its position if the box dimensions change. The current implementation falls short in meeting these requirements. Can anyone offer assistance with this?

Thank you in advance,

Nathan

Answer №1

Give this a try in combination with the code snippet you currently have. To clarify:

jQuery.fn.positionMiddle = function () {
    this.css("position","absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}

$(document).ready(function(){
   $('.box').positionMiddle();
   window.onresize = function(event) {
        $('.box').positionMiddle();
    }
});

Answer №2

-----------------This works---------------------

CSS

       .box{
    width:200px;
    top:-5px; 

    position:relative;
    background:#444;
}
.inner {
    height:0px;
    width:0px;
    background:#444;
    top:50%;
    left:50%;
    right:50%;
    bottom:50%;
    position:relative;
}

.outer { height:200px; width:400px; border:2px dotted red; }

HTML

<div class="outer">
<div class="inner">
    <div class="box">
        wpfw efuiweh fuiwehf weuifh weuifh fuihwe fuihwefuiweh uwehf iuwehf uiwefhweuifh weuifhwe fuiweh fuiwehfuiwefh uiwefh weuifh weuifh weuifhwe uifh weuifhwefuiweh fuiweh fuiwehf iweufh weuih
    </div>
</div>
</div>

jQuery

$(function(){
    $(".box").css('top',-($(".box").height()/2));
    $(".box").css('left',-($(".box").width()/2));
});

If this solution does not meet your requirements, please feel free to reach out. You can also reference http://jsfiddle.net/mazlix/m4Ttk/2/ to observe that resizing the inner and outer divs still maintains center alignment.

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

Implementing Enter key functionality to add items to a Todo list using pure DOM manipulation

var listLis=document.getElementById('list'); const addbutton=document.querySelector('.fa-plus') const inputBar=document.querySelector('.show') function showInput(e){ inputBar.classList.toggle('show') } addbutt ...

Issue with static navigation bar persistence post-page refresh

My scenario involves a navigation bar embedded in the header that should become fixed at the top of the browser window when the document is scrolled down by a certain amount. The script I have been using works well, but it causes an issue in Firefox and C ...

What is the best way to attach an EventListener to all DOM elements with a particular class?

Within my DOM, I have dynamically created spans that all have the class "foo". Utilizing TypeScript, I aim to attach an onClick event to each of these spans post-creation. Here is my current approach: var foos = document.body.querySelectorAll(".foo"); f ...

Is there a way to include a static CSS file in GWT similar to how JavaScript files are included?

I am trying to include a static CSS file, app.css, into my application. When it comes to including JS files, I know how to do it using ScriptInjector like this: ScriptInjector.fromUrl(pathToJsFile) .setWindow(ScriptInjector.TOP_WINDOW) .setCallba ...

Using three.js to manipulate the camera's movement on the geometry generated in Autodesk Viewer from Point A to Point B

I am currently working on transitioning my camera view state from Point A to Point B within the Autodesk viewer. To achieve this, I am creating a path using LineDashedMaterial and have successfully displayed the line connecting Point A and B. Below is the ...

`The challenge of targeting parent elements in jQuery`

I am attempting to target a specific div using the code below: function popupBox($area){ //$mainBox = $(document).createElement('div').attr('id', 'mainBox'); $mainBox = $('<div></div>& ...

Tips for updating the contents of a div dynamically in JavaScript/jQuery without the need for clicking a button or a link

Is there a way to automatically reload or refresh the content of a specific div element without refreshing the entire page, and without any user interaction such as clicking a button or link? I am looking to update the div with the id 'div_graph' ...

Creating a JavaScript array with key-value pairs from a JSON object: Step-by-step guide

Here I have an Object that originates from JSON: ({ "id" : 3, "clientName" : "Avia", "monthlyactiveusers" : 2083, "dailynewlikes" : 0, "totallikes" : 4258, "usersgraph" : { "sTotalLikes" : [{ "likes" : 79, ...

Strange problems arise with bootstrap navigation bar on smaller devices

I'm experiencing a strange issue with my bootstrap navbar that I can't seem to resolve. Whenever I switch to a smaller screen size, this unexpected behavior occurs! The styling isn't anything special beyond the font and text size... https: ...

Within Vuex, the object store.state.activities contains a specific key labeled "list" which initially holds an array of three items. However, when attempting to access store.state.activities.list directly, an empty array

My project is utilizing Vue. The store.state.activities object contains 2 keys, including an array named list with 3 elements. However, despite attempting to access it using store.state.activities.list, I am getting an empty array. I have experimented w ...

Is it possible to update a current HTML value with a dynamically calculated value using HTML, CSS, or both?

While working on generating HTML to be passed back from a REST method, I encountered the following code snippet: StringBuilder builder = new StringBuilder(); builder.Append("<div class=\"row\">"); builder.Append("<div class=\"col-m ...

Tips for showcasing unprocessed JSON information on a webpage

Similar Question: JSON pretty print using JavaScript I am looking to present my raw JSON data on an HTML page similar to how JSONView displays it. Here is an example of my raw JSON data: { "hey":"guy", "anumber":243, "anobject":{ "whoa ...

html/css - techniques for transitioning a centered image on a landing page into a navbar logo when scrolling

Creating a minimalist navbar without the use of JavaScript or custom CSS is easier than you think. <nav class="navbar navbar-expand-md navbar-light bg-faded"> <a class="navbar-brand" href="#"> <img src=&qu ...

Arranging Elements in a Vertical Stack Using Bootstrap

I'm currently working with bootstrap to arrange a series of cards side by side, but I'm facing an issue where the cards end up stacking on top of each other instead of aligning horizontally. <div class="container"> <div class="row"& ...

What could be causing the jQuery spritely animation to display an additional frame upon the second mouseenter event?

I have been experimenting with CSS sprites and the jQuery plugin called spritely. My goal is to create a rollover animation using a Super Mario image. When the mouse hovers over the Super Mario <div>, I want the animation to play forward. And when t ...

Need help using JQuery to set the focus on the initial <select> element on a webpage?

Upon loading the page, I am looking to set focus on the initial element through JQuery. So far, I have managed to achieve this by using: $(":input:visible:first").focus(); or $(':input:enabled:visible:first').focus(); as described in a helpf ...

Reset the input field once the message has been successfully sent

My goal is to clear the form message input field after the form is sent. However, it seems to be clearing the data before it has a chance to be sent. Here is the code I'm using: <script> $(function () { $('form#SendForm'). ...

Problem encountered when private parameters do not match in the constructor

TL:DR: encountering an error Supplied parameters do not match any signatures of call target when trying to utilize private constructor parameters like constructor (private http: Http) {} Running into difficulty while configuring private parameters in Angu ...

Which web browsers are compatible with the input attribute "multiple"?

I am currently incorporating this particular plugin, and its file input does not support multiple file selection. To address this issue, I have added the 'multiple' attribute. However, I am curious if there are any browsers or other platforms (su ...

Altering the properties of the canvas gradient object

let count = 0; let positionX = 960; let positionY = 540; let intervalId = window.setInterval(draw, 100); function draw() { gradient = cxt.createRadialGradient(positionX, positionY, count, positionX, positionY, count + 10); gradient.addColorStop(0, "rgba( ...