Tips for utilizing innerHeight for a div during both window loading and resizing tasks?

I'm currently working on calculating the top/bottom padding of a div (.content) based on its height, and updating it upon loading and resizing the window. The goal is to have it centered nicely next to another div (.character) positioned beside it.

Initially, I attempted using CSS calc, but encountered issues as the syntax didn't support operators. Furthermore, my design includes several media queries adjusting the font size according to the viewport, making the height of the .content div somewhat dynamic.

Here is the JavaScript portion for reference, and you can find the current progress on JSFiddle: https://jsfiddle.net/inochiishtal/a9z13fb2/62/

$(function(){
    $.w = $(window);
    $.w.on('load resize', res);
    res();
});

function res() {
    $('.content').css('height',($.w.innerHeight()/2)+'px');
}

Any assistance or recommendations would be greatly appreciated. If there's a more effective solution than using innerHTML, I'm open to exploring alternative approaches.

Answer №1

The desired alignment of the items is a bit unclear, but based on your description, it seems like you want the .content and .character to be centered vertically with each other.

In the provided code snippet, both elements are positioned absolutely. If this is the approach you'd like to take, you can achieve vertical centering by disregarding margins and JavaScript with the following trick applied to both elements:

top: 50%;
transform: translateY(-50%);

The first line instructs the element to be positioned at 50% from the top of its container. The second line then moves the element up by 50% of its own height. This combination ensures vertical centering based on the parent's size and the element itself.

If both elements are vertically centered within their parent, they will align accordingly.

Check out the example here!

However, if you prefer not to have the elements overlap as shown in the example (which offers a modern look), you can achieve the same result more easily using flexbox.

The parent element should have the following CSS properties:

display: flex;
align-items: center;

And the two child elements should have:

flex-basis: 50%; //to give them width

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

The functionality of tinymce setContent can only be activated by directly clicking on it

Everything is running smoothly with the code below: $('.atitle').on('click', function(){ console.log('323'); tinymce.get("ed").setContent("<p>lorem ipsum</p>"); // it's working ...

JQuery Function for Repeatedly Looping through Div Elements

I've been experimenting with creating a loop that alternates the fade-in and fade-out effects for different elements. This is what I have so far: setInterval(function() { jQuery(".loop").each(function(index, k) { jQuery(this).delay(1200 ...

Updates to props values are not being reflected in the React js application running on the webpack

I keep facing an issue where I have to restart the webpack server every time I try to pass or update props values from parent to child components. It's frustrating that the props values are not updating even after saving the file. Take a look at my p ...

CSS: Caption text below image remains on same line

I am struggling with positioning a div that contains an image and a caption. My goal is to make the caption break into a new line when it reaches 95% of the width of the image. Despite my efforts, I can't seem to achieve this. The text always pushes ...

Interacting with JQuery UI Button causes it to shift position on mouseover

In my table, there are two large cells. The left cell contains two drop-downs and a JQuery UI button that is causing trouble, while the right cell displays a list generated from an AJAX database query. As the list grows longer, the button gradually moves u ...

Stop an animation while it is in the hover state

Currently experimenting with CSS3 Animations to create a Panoramic view using only CSS and no JavaScript. I have managed to create a somewhat working demo: http://www.example.com/images/panoramic/ The concept is simple: when the user hovers over the blac ...

KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array: "objects": [ { "category": "XXXXX", "item_name": "over_pkg_0", "price": 230 }, { "category": "XXXXX", "item_name": "over_pkg_1", "price": 54 }, ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Can anyone suggest a method to block the execution of Javascript commands in the console?

Regarding the inquiry mentioned in the question title. Is it possible to prevent individuals from executing functions on my webpage using the console, even though it is not necessary? I have experimented with various methods, and the code below represent ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Is the page wrapper failing to contain or wrap anything at all?

Having a bit of trouble with my div element not wrapping all the way down. To simplify things, I've applied borders and background colors to everything. Here's the HTML code... I could resort to adding a float left to the page-wrapper div as a w ...

Using NextJS to Load Fonts from a Database

I've implemented a feature in my NextJS and Tailwind CSS app that allows users to select a theme with different color schemes and font options. The fonts available are all from Google Fonts. However, I'm facing an issue with loading the selected ...

Convert this JavaScript function into a jQuery function

I currently have this JavaScript function: function removeStyle(parent){ var rmStyle = document.getElementById(parent).getElementsByTagName("a"); for (i=0; i<rmStyle.length; i++){ rmStyle[i].className = ""; } } Since I am now using ...

conflicting character encoding systems

Request normally comes in this format: Parameters: {"utf8"=>"✓", "status_id"=>"12686"} However, from one particular client, the request looks like this: Parameters: {"utf8"=>"\xE2??", "status_id"=>"12686"} As a result, I am encounter ...

Exploring how to iterate through multiple arrays simultaneously in JavaScript

I have a specific problem with processing two sets of array objects to achieve a desired output. var parts={"Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [14], "Jerom":[15,25,35], }; var labor={ "Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [ ...

Material UI - Utilizing multiple CSS classes within a unified global theme

Exploring the world of Material UI within React for the first time has been an exciting journey. I am currently looking to customize my global theme, specifically targeting two classes: .MuiListItem-root.Mui-selected, .MuiListItem-root.Mui-selected:hover { ...

Extract CSS properties to generate a dictionary that maps class names to background images

Suppose my CSS looks like this: .featured .featured_1 { background-image: url("http://test.com/image.png"); margin-top:20px; } In that case, the following PHP function: function extractBackgroundImages($css) { if (!preg_match_all('/&bso ...

Is there a way to launch iframe links in the parent window of an Android native app?

I'm currently working on developing a directory-style application, and I am using iframes to embed other websites into the app. I would like the embedded site links to open within the parent window. In the Progressive Web App version, everything is w ...

Retrieve information attribute within VueJS

Within a v-for loop, I am utilizing a select form in the following manner: <div class="select"> <select v-model="shippingMethod"> <option value="{{shipping.id}}" v-for="shipping in shippingMethods" data-price="{{ shipping.amount ...

What is the method for choosing multiple IDs using CSS?

Is there a way to target multiple IDs in CSS? For instance: #test_id_*{ } <div id="test_id_10"></div> <div id="test_id_11"></div> ...