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

Tips for showing a variety of headers on your page

I am struggling to align multiple headers on the same horizontal line. Despite my efforts, only two of them display correctly while the third keeps dropping down a line. To see what I mean, take a look at this image: view current layout Here is the code ...

Dynamic color change in SVG

I am facing an issue with changing the color of svg images in a menu list using the filter CSS property. Even though I have obtained the correct filter value from a library that converts hex to CSS filter, React seems unable to set this property on the ima ...

Error message: Next.js - Unable to access properties of an undefined object (user)

I am currently utilizing Next.js and Next-auth in my current project. Within this project, I am working on creating a Sidebar component that will display a list of items specific to each user. To achieve this, I am using the useSession hook to retrieve t ...

Exploring the flow of resolve promises in UI-router from the main root state to its sub-states

Currently, I am in the process of developing an Angular application with ui-router. The first step I took was to create a root state that serves as an abstract one intended for resolving asynchronous dependencies. This means that any subsequent sub-states ...

Avoiding server requests in Firefox by refraining from using ajax

I've implemented the following jquery code: $("#tasksViewType").selectBox().change( function (){ var userId = $('#hiddenUserId').val(); var viewTypeId = $("#tasksViewType").val(); $.post('updateViewType& ...

What could be causing my AngularJs routing and animation to bypass the second redirection?

Recently started working with Angular and experimenting with routing and animations to manage my page transitions. I followed a helpful guide that helped me set everything up. I encountered a few issues: When trying to link back to the landing page (home ...

The CSS class names for Next.js have not been defined yet

Just getting started with next js and trying to use css modules for styling my nav component. However, I noticed that the classname I setup for the nav element is not showing up in the rendered DOM. Even though I can see the generated styles by webpack in ...

Is there a method in ASP MVC to generate an object dynamically within the view that corresponds to the model and can be mapped to input fields for sending via Ajax?

Details of the Model: public class MyDerived: Base { public string FirstName { get; set; } public string LastName { get; set; } } Description of Controller's Action Method: [HttpPost] public ActionResult Add(MyDerived obj) { if (ModelSt ...

Dynamic Content Sorting with JavaScript and jQuery

I am presenting various courses that are available, and I am utilizing JavaScript/jQuery to display or hide them based on element classes. You can view the page here. Currently, the script conceals all content on the page and then reveals items that matc ...

Designing an interactive header interface using React and Material UI

My header.jsx file contains the following code: // Default Import Statements var Login = require(login.jsx) const HeaderComponent = React.createClass({ getInitialState () { return { loggedIn: false, }; }, render() { return ( ...

Exploring the contrast between a hidden element and an element positioned outside the viewport through Selenium testing

When a selenium element is disabled by the ng-show attribute being false, it will have the values Displayed=false and Enabled=true. However, if a selenium element is enabled with the ng-show attribute set to true but is out of the viewport, it will also ha ...

Having trouble with the ::after element in my React component for my latest React 3D portfolio project

For my portfolio project, I am following a tutorial by LamaDev (https://www.youtube.com/watch?v=qALsVa-V9qo&t=2334s&ab_channel=LamaDev). At around timestamp 36:40, he creates a ::after selector which is not working for me, even though the rest of t ...

Difficulty arises in bookmarking slug paths within Next.js SSG

I am currently managing a next js SSG exported application that is operating in nginx. My objective is to transfer it to S3 in the near future. However, I have encountered an obstacle where the slug paths cannot be bookmarked in a browser. Although the ro ...

Why is URL Hash Navigation not functioning when linking to a different page's slide on the carousel?

Why isn't the #tag link being recognized? Even though the data-hash items are visible in the URL window, the script doesn't seem to pick them up. The standard script used on the carousel page is as follows: $(document).ready(function() { $( ...

Adjust the field's color depending on the outcome displayed within

I'm trying to implement a feature where the field value changes to green when "OK" is selected and red when "NOK" is chosen. I have written the following JavaScript code but it's not working as expected - the colors change before clicking submit, ...

What is the process of uploading a file from a Vue.js app to the local public disk in Laravel?

Hello there, I am looking to upload a file from a Vue.js app to the local public directory of Laravel and only store the unique name in MySQL upon form submission. However, I am unsure how to achieve this using JavaScript. // Template Tag <input type= ...

How does using position: fixed affect width in React components?

Can someone explain why my sidebar width is reduced when I apply position: fixed? Here is the code snippet: https://codesandbox.io/s/1yr3nlqp74 Steps to reproduce the bug: Open the code in a new window (full screen) Observe the picture before and after ...

Code functioning properly on JS Fiddle, experiencing difficulties when running directly in browser

Hey there, I have this vertical jquery tabs example working on JSFiddle, you can check it out here: https://jsfiddle.net/tj_vantoll/nn2Qw/ I've been trying to replicate it in an HTML file but so far I haven't had any luck... Can someone help me ...

Alter the hues of the triangles on a threeJS plane

Is there a way to create a multicolor plane by changing the colors of the triangles within a mesh? Can the colors of triangles be adjusted in a PlaneGeometry object? ...

"How can I dynamically set the text for a radio button using Reactive Forms? Also, how do I capture the selected radio button value and the question title

If I use a reactive form-array, can I dynamically add 2 questions and 3 or 4 choices? Question 1: How do I set the radio button text dynamically using form-array? Question 2: Now, I'm attempting to retrieve only the selected choice ID corresponding ...