Applying custom CSS to individual divs based on their text height using jQuery

I have a grid consisting of multiple boxes each sized at 280px by 280px, and I am seeking a way to vertically align text within hover overlays on each box.

While my current code successfully aligns the text for the first box, I am encountering issues due to varying text lengths and heights for each box. I am looking to create a function that dynamically assigns top padding based on the specific paragraph height within each box.

I believe using the .each method could help me achieve this, but my attempts to implement it have been unsuccessful.

Presented below is the code that currently works and requires modification to target each box individually:

    var txtHeight = $( ".login-item .lgn-overlay p" ).height();
    var topPadding = ((284 - txtHeight) / 2);
    $('.login-item .lgn-overlay').css('padding-top', topPadding);

Answer №1

$('.login-item .lgn-overlay').each(function(){
    var $this = $(this);
    $this.css('padding-top', function(){
        return ((284 - $this.find("p").height()) / 2);
    });
});

Let's give this a shot. I crafted this code on the planning page, so please point out any errors if you find them.

Answer №2

Consider implementing a solution like the following:

//calculate this dynamically 
var requiredLength = 200;
$('.login-item .lgn-overlay').each(function () {
   //this refers to each element
   var $this = $(this);
   var currentLength = $this.outerHeight();
   var extraLength = requiredLength - currentLength;
   var additionalPadding = extraLength / 2;
   $this.css('padding-top', additionalPadding);
});

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

Transform JSON headers and rows into Object keys using Node.js

I am currently working on retrieving data from an API in JSON format using Node JS. The JSON data consists of headers and rows, including information such as "Vendor, Price, SKU, Error" (see the attached screenshot). I am looking to structure this data int ...

How do the authentication and authorization processes in my frontend connect with the backend of my API system?

Currently, my frontend is built with Vue while my backend relies on an express rest API that fetches data from mysql. My goal is to ensure security for both the frontend (specifically a login form) and backend API without limiting access solely to my front ...

A single Modal, Ajax, and data that is continuously refreshed

I'm currently facing a challenge in my project as I try to implement Ajax functionality. Although I'm relatively new to using it, I believe I have a basic understanding of its workings. My website involves collecting form data, posting it to a d ...

In Javascript, an error occurs when something is undefined

I've been grappling with a Javascript issue and seem to have hit a roadblock. In Firefox's console, I keep encountering an error message that says "info[last] is undefined," and it's leaving me puzzled. The problematic line appears to be nu ...

Timer countdown: Looking for a countdown timer that will reset to 3:00 automatically each time it reaches 0 minutes, and can do so

Seeking a continuous countdown timer that starts from 03:00 and counts down to 0:00, then automatically resets back to 03:00, in an infinite loop. The condition is that no one should be able to manually stop this logic. After researching, I found a Ja ...

AngularJS's $resource module returns an empty array as a response

I am trying to display a table with items from JSON data. I have created a Service that returns the JSON data. In my controller, I am querying the Service to receive an array of data. It's a little confusing because I am putting the response in a new ...

The issue of React Js's inline style malfunctioning when using a loop condition

Having some trouble with setting different backgrounds for items in a loop in React JS. I attempted to use inline styles to make it dynamic, but no luck so far. Any tips or solutions? { main.map((item, index) => ( <a key={index} href=&apo ...

What is another option for object-fit: cover?

Is there a way to resize an image on my webpage while maintaining its aspect ratio based on the screen size? I want the smaller dimension (width or height) to fit exactly within the element, with the larger dimension overflowing. I came across the objec ...

Adding a MTL texture to an OBJ in your three.js project is a simple process that can enhance

Hello! I am currently working on adding an MTL file to my OBJ in three.js. I had successfully loaded my OBJ and went back to address this issue. However, after adding the code to load the MTL file using MTLLoader, the code seems to be getting stuck at mt ...

Step-by-step guide on implementing a dynamic edit and delete feature for individual data entries within jQuery dataTables

Here is the HTML table code I have: <table id="datatable-buttons" class="table table-bordered" style="overflow: hidden;"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> ...

How can AngularJS utilize ng-repeat and ng-bind-html to display arrays of HTML strings?

I'm currently attempting to display HTML strings from an array of HTML strings in my AngularJS project. As a newcomer to AngularJS, I have been trying to follow the examples provided on the official AngularJS website, but I am struggling to find a sui ...

Centering text within a dynamic div can help create a visually appealing design

While browsing through various forums, I noticed several questions on stackoverflow that touch upon a similar issue to mine. However, my particular problem is a bit unique, and despite my best efforts, I have not been able to find a solution yet. It's ...

Following conventional methods often results in oversized containers and monolithic code

I've heard that it's recommended to use classes for containers and functions for components. Containers handle state, while components are simple functions that receive and send props to and from the containers. The issue I'm encountering i ...

Adjust the size of an image post-render with the help of Angular or jQuery

Below is my current HTML code: <img width="150" height="150" src="https://d.pcd/image/578434201?hei=75&amp;wid=75&amp;qlt=50,0&amp;op_sharpen=1&amp;op_usm=0.9,0.5,0,0" ng-src="https://d.pcd/image/578434201?hei=75&amp;wid=75&amp; ...

What is the best way to fill cascading dropdown lists with data fetched through ajax requests?

I attempted to create a CRUD web page with two cascading dropdown lists. Everything works smoothly when saving the data, but when retrieving it, the second dropdown list remains empty. Even after trying to populate the second dropdown list once the code i ...

Is there a way to modify the appearance of a particular element in ng-repeat?

On my website, I am using ng-repeat to display various dish postings. I want to trigger a modal to open when I click on a dish, showing the specific data for that dish. To achieve this, I'm assigning each dish a modal div with a unique ID (dish-$index ...

Does React include a mechanism for event dispatching and listening?

Recently, I've been exploring the intricacies of the Laravel framework and have been fascinated by its event dispatching and listening system. In the past, I've dabbled with electron which shares similarities with Laravel's system, but in m ...

Encountering an error when using Angular Material virtual scroll in conjunction with Angular-UI

Trying to incorporate Angular material's virtual scroll feature on angular-ui-tree is proving to be a bit challenging. The error message that keeps popping up is: Controller 'uiTree', which is required by directive 'uiTreeNode', ...

Jquery does not display the variable in the Firefox console using console.log

I am trying to retrieve the data value from the text input, but it's not getting logged in the console. I even tried using a breakpoint, but it still doesn't console anything. What could be the issue? var x = '' $(() => { $("#en ...

TypeScript - Indexable Type

Here is an explanation of some interesting syntax examples: interface StringArray { [index: number]: string; } This code snippet defines a type called StringArray, specifying that when the array is indexed with a number, it will return a string. For e ...