skip to Main Content

I’m trying to figure out how can I turn an element’s undefined (auto) height into a variable… so that I can use it in a calc function.

I’ve got a two column div. The left column, is a text div with an undefined height (height: auto). The right column, is an image, but the image column’s height needs to be greater than the text column’s height for it to look good.

Is there a way I could set the right column’s height to something like the following?:

/* Let's pretend this left column's height is 463px */
.column.left {
  height: auto;
}

/* And the goal for this right column's height would be 543px */
.column.right {
  height: calc(var(--col-left-height) + 80px);
}

So would it be possible to grab the height of the left column & turn it into a variable without setting a fixed height? I’ve attached an image of the actual layout I’m doing for this project, thank you so much for the help!

Image example of the layout:

enter image description here

2

Answers


  1. You can use JavaScript to get the actual height value of an element:

    const leftDiv = document.querySelector(".column.left");
    const rightDiv = document.querySelector(".column.right");
    
    // get height of left column
    const leftDivHeight = leftDiv.offsetHeight;
    
    // set height of the right column: "left column + 80px"
    rightDiv.style.height = leftDivHeight + 80 + "px";
    
    Login or Signup to reply.
  2. No, it’s not possible.

    But if you use a grid to create your columns, the default is for the grid items in those columns to stretch vertically to fit their content. So the height of the grid, and therefore the height of both columns, is determined by the column with the longest content.

    What you could do in your case is to add an 80 pixel bottom padding to the item in your first column, so that means that the height of both column items will become 80 pixels higher than the content in your first column. So this essentially implements the calculation you are wanting to do.

    All that then remains to be done is to give the content inside your second column a height of 100%. You may need to wrap this content inside an additional div in order to do this easily.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search