The height of divs spontaneously changes after resizing without any instructions

I am developing a jQuery function to vertically center an element. The function is triggered on load and here is the code:

JQuery

var $window_height;
function Centerize(content) {
    content.css('margin-top', (($window_height - content.height())/2))
};

$(function(){
    $window_height = $(window).height();
    Centerize($('#welcome'));

    $(window).on('resize',function(){
        $window_height = $(window).height();
        Centerize($('#welcome'));
        });
})

However, I encountered an issue where upon resizing the window, the height of my div changes unexpectedly (decreases by 60px). This results in the margin-top increasing, pushing the entire div downwards.

I have verified this by using console logs for $('#welcome').height().

The initial value is 432px. After resize, it drops to 361px and remains so even when maximizing the browser window. Any suggestions?

SCSS:

#welcome {
    margin: 0 auto;
    background-color: #DB9E36;
    border-radius: 30px;
    width: 800px;
    padding: 30px 50px;
    text-align: center;

    div {
        margin: 50px auto;
        background-color: #FFE34E;
        width: 300px;
        height: 50px;
        border-radius: 5px;
        a {
            display: inline-block;
            text-decoration: none;
            font-family: 'Quicksand', sans-serif;
            font-weight: bold;
            color: #FFFAD5;
            background-color: #BD4932;
            width: 100px;
            margin: 10px 10px;
            padding: 5px 0;
        }
    }
}

Answer №1

Before jumping into jQuery/JavaScript for vertical centering, have you considered a CSS-only approach? Simply using top: 50%; margin-top:-100px can achieve the same effect by adjusting the margin to half the height of your content. Check out this demo: http://jsfiddle.net/lasha/dGcsB/

If you prefer using jQuery, you can dynamically apply similar CSS as shown in your code attempt. Here's a demo with jQuery implementation: http://jsfiddle.net/lasha/dGcsB/1/

You can also center an element within a parent container that changes height dynamically using a similar technique: http://jsfiddle.net/lasha/dGcsB/2/

Feel free to explore the provided code samples. :)

EDIT: It's worth noting that issues with height calculation may arise in Chrome due to the 'ready' event firing before the DOM finishes calculating dimensions of elements. In such cases, accessing height or width on load may not reflect the correct values. This issue is more common in Chrome and less so in Firefox.

Answer №2

It seems like the issue could be related to images being contained within your #welcome div. You might want to consider replacing:

$(function(){
    $window_height = ...

with

$(window).on('load', function () {
   $window_height = ...

This change will allow enough time for the images to fully load before executing the script.

Answer №3

Did you attempt to adjust the height of the greeting section? When you resize the browser, it's possible that the section will also resize since its height is not specified.

#greeting {
    margin: 0 auto;
    background-color: #67B1E4;
    border-radius: 20px;
    width: 700px;
    padding: 20px 40px;
    text-align: center;
    height:150px;
    ...

Try testing if this change affects the issue you are currently experiencing

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

Using ng-include destroys the styling of the dropdown menu in a bootstrap ul li format

Greetings! I am attempting to replicate the following code snippet that creates a basic dropdown menu using bootstrap: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="fal ...

Maximizing efficiency with JavaScript object reduction

let students = [ { name: "john", marks: 50, }, { name: "mary", marks: 55, }, { name: "peter", marks: 75, }, ]; I need to find the total sum of marks using the reduce method. Here is my att ...

The size of the Tweet button iframe is set at 107 pixels

Has anyone been able to successfully adjust the size of the tweet button generated by Twitter's iframe code? My attempts have resulted in a default width of 107px, but I need it to match the actual button size. I've tried adjusting the CSS proper ...

Preventing jQuery from loading a div if it already exists: a step-by-step guide

I've encountered an issue with a mock console on my website - every time the same input value is submitted more than once, jQuery reloads the div due to its specific id. Instead of cloning the div, I decided to append a message indicating that it alr ...

`json: Alert not displaying response data`

Currently, I am utilizing the following Ajax code to retrieve data from the server. $.get("http://***/umbraco/Api/SomeApi/SignIn",{apiVersion : 1,email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee0efe3ebcee9e3efe7e2a0ed ...

Add a .handlebars or .hbs file to an HTML document

When visiting the emberjs.com homepage, you will find an example of a todo list using Ember.js and Handlebars.js. Within the todo list, there is an extension for a .hbs file. I am curious - what exactly is a .hbs file? And how can I include a .hbs script ...

Angular Chart.js is throwing an error: "Uncaught SyntaxError: Cannot use import statement outside a module"

Upon opening the page, an error in the console related to Chart.js 4.2.1 is being displayed. Description of first image. Description of second image. Is it possible that this issue solely lies with Chart.js? How can it be resolved? To address the proble ...

Is it possible to use JavaScript to clear a field that was generated by Yii CRUD?

Issue with Yii's GRUD field generated and Firefox HTML: <?= $form->field($model, 'productId')->textInput(['maxlength' => true]) ?> Comparison of PHP generated code to Firefox HTML: <input id="taolistforcreate-p ...

document ready function in the Microsoft AJAX client side library

The Microsoft AJAX client-side library contains various functions that imitate the server-side Page Life Cycle and conditions like if (!Page.IsPostBack). I am unsure about which client-side function corresponds to the equivalent server-side method. What is ...

Is there a way to prevent users from copying data or switching tasks when using my program or website?

Is it feasible to develop a website or application for Windows desktop machines that can remain focused until the user completes a specific task? For instance, if my YYY app/website is open and I require the user to input some text, I want to restrict the ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

Issue with binding the deepest level grid in a two-level deep Kendo Grid detail template

Encountering an unusual issue with the Detail Template in Kendo Grid. My setup includes two levels of Detail Templates, which have been functioning correctly most of the time (although it sounds peculiar). However, there are instances where the innermost g ...

The database is not being updated with the new values

Is it possible to retrieve data from a database and modify it using AJAX? I tried changing the input, but AJAX keeps sending the original data stored in the database. <script> function showMore(str) { var xhttp; if (str.length == ...

Creating Vue components and including Javascript code within them

Attempting to develop a component using Vue for my JavaScript code, but encountering issues. My primary aim is to build a component with either Vue or Vue3 <head> <title></title> <script src="https://cdn.jsdelivr ...

Moving a component beyond its container using a query

After much searching, I have yet to find a solution to fix this issue. My problem involves having a list with draggable elements within a scrollable area. The goal is to drag these elements outside of the parent div into a droppable area; however, they see ...

What strategies can be implemented to avoid PHP timeouts when running loops, without adjusting the max_execution_time setting?

I am facing a challenge with a folder full of documents that need to be processed by a PHP script. There are around 1000 documents in the folder, and each one needs to be deleted after processing. Is there a way to efficiently run or restart a PHP script ...

Experience unique website functionalities across Windows/Android and Apple ecosystems

Apologies for any language errors in advance. I'm facing an issue where my website appears differently on Safari or Chrome on iOS/MacOS compared to Windows 10 or Android devices. If you observe the List of Receiving Countries in the images provided: ...

Is there a way to prevent HTML Tidy from inserting newlines before closing tags?

Have you ever noticed how HTML Tidy always seems to add an extra newline before the closing tag? It's so frustrating! For instance: <p>Some text</p> ends up looking like this: <p>Some text </p> Is there a way to make Tidy k ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

Issues with NextJS detecting environmental variables

I recently encountered an issue with my NextJS app running on Next.js v12.2.5 where it appears to be ignoring the environment variables I've configured. To address this, I created a .env.local file with the following content: NEXT_PUBLIC_SERVER_URL=h ...