Is there a way to transfer div height from JavaScript to CSS?

Is it possible to dynamically set the position of a div based on its own height, which can vary depending on the content inside?

Here is an example structure:

HTML

<div class="container">
Content
</div>

CSS:

:root {
  --height: x;
}

.container {
height: auto;
top: calc(100vh - var(--height));
}

Answer №1

.clientHeight function returns the height of an object, which I then assign to a CSS variable.

 let container = document.querySelector(".content")
        var root = document.querySelector(':root');
        root.style.setProperty('--height', container.clientHeight + "px");
:root {
        --height: x;
    }

    .content {
        outline: 1px solid red;
        height: auto;
        position: relative;
        top: calc(100vh - var(--height));
    }
<div class="content">
        <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptatibus, officiis! Lorem ipsum dolor sit amet
            consectetur, adipisicing elit. Dolore accusantium deserunt corrupti iure praesentium in reprehenderit
            placeat mollitia culpa labore nostrum, cumque obcaecati et sapiente dolores excepturi libero maiores
            arch</p>
    </div>

Answer №2

If you want to modify a CSS variable called --height using JavaScript, you can do so by:

var root = document.querySelector(':root');
root.style.setProperty('--height', <YOUR_HEIGHT>+'px');

Check out this quick demo where we update a CSS variable named --width when a button is clicked:

var root = document.querySelector(':root');
root.style.setProperty('--width', '100px');

function changeSize() {
  if (getComputedStyle(root).getPropertyValue('--width') == '100px') {
    root.style.setProperty('--width', '200px');
  } else {
    root.style.setProperty('--width', '100px');
  }
}
:root {
  --width: 100px
}

div {
  height: 100px;
  width: var(--width);
  background-color: blue;
}
<div></div>
<button onclick="changeSize()">Change variable value</button>

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

Slow CSS :hover animations in the most recent release of Chrome

I recently upgraded my browser from chromium version 67 to the latest Chrome version 79. However, I noticed that after the upgrade, the CSS transitions on my website have become very laggy and unresponsive. Surprisingly, everything works perfectly fine on ...

Problem with keydown event in jQuery on Android mobile browser

I am attempting to have a textarea respond to keydown events. I experimented with the following code: <textarea id="text"></textarea> $('#text').keydown(function() { alert('keydown'); }); While this works well on deskto ...

Create a form with two divs inside: one positioned in the middle and the other at the bottom

I have organized a responsive form of div with a central and bottom alignment. The code I have included is as follows: <link href="../css/bootstrap-theme.min.css" rel="stylesheet" /> <link href="../css/bootstrap.min.css" rel="stylesheet" /> &l ...

Is it possible for a CSS code to be universally effective across all PHP files by setting style.css in header.php and then including header.php in each of the other PHP files?

Let me confirm, the code snippet from the header.php file is as follows: <link rel="stylesheet" href="style.css"> If I include the following code in every other php file: include 'header.php'; Will all the files have access to style.css ...

Pass data from viewmodel back to controller in C# MVC

One of the challenges I am facing is in a view that allows users to add items to a table. Using a simple HTML form and jQuery, new rows are dynamically added to the table. I am seeking a way to efficiently pass the added rows from the view to the controll ...

Experimenting with @media queries to dynamically resize images for various devices such as phones, tablets, and desktop

I'm struggling with making the background images on my website responsive. I have already added media queries to my page, but they seem ineffective and I am unsure of what else to try. Below are the HTML and CSS codes for the three images. Any suggest ...

Developing a custom library to enable Ajax capabilities in web applications

Currently, I am in the process of developing my own personal library. jQuery doesn't quite meet my needs, and I prefer having a clear understanding of what is happening within my code. Nevertheless, I'm encountering an issue with the ajax functio ...

Implementing a Laravel Ajax filter using radio buttons

I'm currently working on implementing an Ajax post filter using radio buttons. The goal is for the user to be able to filter through two published products by selecting the appropriate radio button. Below is the code I have utilized: category.blade. ...

Zebra Striping Tables with jQuery and Concealed Rows

Up until now, I haven't had any issues using the following code: $("#tableid tr:even").addClass("evenClass"); However, my table now contains hidden rows which is causing problems with the alternating row styles. I've attempted to add 'is(" ...

"Perpetual access to color selection through the input type

Can you assist me? I am currently using the input type color and looking to have the color picker always visible without requiring a click. Is there a way to achieve this through html, css, javascript/jquery, or any other method? Thank you in advance. I ...

Sliding the cursor downward to unveil a panel? (utilizing MooTools)

I'm looking to implement a feature where a DIV panel slides in when the user clicks and drags a smaller tab. While there are tutorials available for sliding elements on click, I specifically need the panel to slide in only when the user interacts with ...

Obtain several dropdown menus without their items displaying beneath the correct element

I'm currently in the process of setting up multiple drop down menus within a navigation element. The issue I'm facing is that when a user hovers over the menu items, the displayed elements appear below the first item instead of the selected one. ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

Difficulty with the responsiveness of a website due to issues with the bootstrap grid system

I've been working with a Bootstrap grid that you can find at . While it works perfectly on large desktop screens, everything is a bit messy on mobile devices. The "NEW" text specifically is not visible on mobile and doesn't seem to be responsive. ...

In the ajax call, an empty JSON array object is sent as the data

Utilizing JSON data as a parameter for an ajax call: var startDate = dateFormatForSave($("#start_date").val().trim()); var arrayOfStudentsInfo = []; var table = $("#selected_students"); table.find('tr').each(function(i, el) { var rowId = $( ...

Displaying the "Ad Blocker Detected" image next to the advertisement

I am attempting to create a feature where if adblock is enabled, an image will display behind the ad banner on my website with the message "Please consider disabling adblock". Unfortunately, it is only showing up as a bordered box. Here is how the box ap ...

Is there a way to update a field or submit a form without having to redirect or refresh the page?

I am struggling to find the right solution for updating just one field in my database called Flag, which is a Boolean field. I have tried using ajax/JQuery, but it only works for the first item in the list and stops working for subsequent items. The ID and ...

CSS3 family tree tutorial: Incorporating a wife into the design

I came across a fascinating tutorial about creating a family tree using CSS3 only. However, I'm struggling to understand how to depict a marriage. To explain further: What the code currently accomplishes is this: what i aim to include is this: Alth ...

Problem with the swipe direction in Flexslider when right-to-left language

I have integrated the flexslider with rtl support from a website called rtl-this.com. However, I am facing an issue where when swiping the slider on touch screens, it moves in the opposite direction. Can anyone suggest a solution to fix this problem? ...

Tips for capturing a webpage thumbnail using a combination of jQuery and PHP from a specified link

Is there a way to capture a web page thumbnail using jQuery and PHP for a specific link? Imagine if I were to assign a PHP variable like this: $screen="http://www.yahoo.com" Can we implement the use of AJAX, jQuery, and PHP to display a thumbnail of the ...