The young ones whose height is 80% that of their taller parent's

Achieving the Desired Height

In order to set a div with 80% of the height of its parent element without a defined height, I am aiming for a responsive effect.

The Layered Layout Issue

Within my layout consisting of five layers - .header, .site, .container, .right sidebar, and .left content, I am facing a challenge. The header has a fixed height of 50 pixels, while the site's height is determined by the viewport height minus the 50 pixels from the header. Inside the site's div, there is a container that I want to set at 80% of the remaining space after considering the header and site dimensions, but I'm struggling to achieve this using percentages instead of fixed pixels.

View the Problem on FiddleJS

Check out the issue demonstration here.

Technical Analysis

The current solution works flawlessly when pixel values are used. However, changing the height of .left-content to 80% reveals the underlying problem due to the dependency on absolute pixel measurements.

Code Snippet (Same as in FiddleJS)

HTML:

<div class="header">
</div>
<div class="site">
    <div class="container">
        <div class="container-head">
        </div>
        <div class="container-body">
            <div class="right-sidebar">
                Just a menu will be right here.
            </div>
            <div class="left-content">
                <ul>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                </ul>
            </div>
        </div>
    </div>
</div>

CSS:

body {
    font-family: Tahoma
}

.header {
    background-color: #49c98e;
    width: 100%;
    height: 50px;
}

.site {
    padding: 1.5em 0;
}

.container {
    background-color: #c7c7c7;
    width: 95%;
    margin: 0 auto;
    position: relative;
}

.right-sidebar {
    background-color: #a94cd5;
    width: 300px;
    height: 100%;
    position: absolute;
    right: 0;
}

.left-content {
    background-color: #dbdbdb;
    width: 100%;
    height: 500px;
    overflow-y: scroll;
}

.left-content ul {
    padding: 25px 0;
    float: left;
}

.left-content ul li {
    background-color: #a94cd5;
    width: 150px;
    height: 100px;
    float: left;
    margin: 15px;
    list-style: none;
}

jQuery/JavaScript:

function calculateResponsiveWidth() {
    $realWidth = $(".container").width() - $(".right-sidebar").outerWidth(),
    $containerContent = $(".left-content");

    $containerContent.css({
        "width": $realWidth
    });
}

$(window).on("resize", function () {
    calculateResponsiveWidth();
});

calculateResponsiveWidth();

Your insights are much appreciated.

Update v1

I am starting to consider that utilizing percentage values may not offer the most optimal solution. Post-container spacing of 25 pixels is necessary, which does not scale well across different resolutions. A Media Query suggestion was made, but I require a JavaScript-based alternative compatible with Internet Explorer 8. Any suggestions or solutions?

Update v2

The identified issue has been overcome through strategic application of JavaScript, mathematical calculations, and logical reasoning. Grateful for all contributions!

Answer №1

To ensure that the container div's height is correctly understood as 80% when applied, you must set height:100%; on the html, body, and site div. Once this is done, the fiddle should work as intended.

http://jsfiddle.net/fvU5d/3/

If your intention was for the container div to be 80% of the site div rather than the viewport, please clarify.

EDIT

Here is a suggestion (http://jsfiddle.net/fvU5d/5/):

var newHeight = $(window).height() - 50;
newHeight = newHeight + 'px';
$('.site').css('height',newHeight);

Answer №2

The parent element does not have a defined height, causing confusion with percentages. The element is set to be 80% of an unknown value.

To resolve this issue, I adjusted the height to 80% and specified a height for its parent element.

You can view the updated code snippet here.

.container-body{
    height: 600px;
}
.left-content {
    background-color: #dbdbdb;
    width: 100%;
    height: 80%;
    overflow-y: scroll;
}

Answer №3

Optimizing React Components

When dealing with a parent div of unknown height in React, it's crucial to determine the height of the parent dynamically before utilizing percentages. This approach gives you control over the parent's height, allowing you to adjust the child element accordingly.

JS Fiddle Demo:

Check out this code snippet for reference!

How to calculate the parent's height:

document.getElementById('div-to-calculate').clientHeight

The above line only fetches the initial height of the div. To update the height on window resize, additional steps are necessary.

  1. Maintain the height value in state.
  2. Add an event listener that detects window resize and updates the height state accordingly.
  3. Apply the calculated height to the parent container, ensuring it has a definitive height.

Your implementation might resemble the following structure:

class App extends React.Component {
  constructor() {
    super()
    this.state = {
      height: null
    }
  }

  calculateHeight = () => {
    this.setState({height: null}, () => {
      const height = document.getElementById('div-to-calculate').clientHeight;
      this.setState({ height })
    });
  }

  componentDidMount() {
    this.calculateHeight();
    window.addEventListener("resize", this.calculateHeight);
  }

   componentWillUnmount() {
     window.removeEventListener("resize", this.calculateHeight);
   }


  render() {
    return (
      <div style={{display: 'flex', flexDirection: 'column', minHeight: '100vh'}}>
        <div style={{flex: '0 0 50px', backgroundColor: 'blue'}}>Header</div>
        <div id="div-to-calculate" style={{
          flex: '1 0 auto',
          height: this.state.height ? `${this.state.height}px` : null
        }}>

          <div style={{ display: 'flex', height: '100%' }}>
            <div style={{ flex: '1 0 auto', backgroundColor: 'yellow' }}>
              <div style={{
                textAlign: 'center',
                width: '250px',
                margin: '0 auto',
                border: '1px solid black',
                position: 'relative',
                top: '50%',
                transform:'translateY(-50%)'
              }}>
                Middle Section
              </div>
            </div>
          </div>
        </div>
        <div style={{ flex: '0 0 50px', backgroundColor: 'blue'}}>Footer</div>
      </div>
    );
  }
}

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

Angular does not adhere to globally defined styles

I have defined the margins for mat-expansion-panel in my styles.css file as follows: mat-expansion-panel { margin: 2vh; } Unfortunately, these margins will not be applied to my components unless they are also specified in the local CSS file. Even try ...

Using jQuery to create a draggable element with a visual indicator that represents a link between two items

Utilizing the "parenting" tool in Adobe AfterEffects allows you to connect layers together. Simply click and hold the icon, then drag it to its destination. A line is drawn from the parent layer to your cursor as a visual guide. I have mastered draggable/ ...

Is there a way to create a table that has varying columns for each row?

I am currently working with bootstrap4 and I am trying to create a table that has 3 columns in the first row and 4 columns in the following two rows. I want it to look like this: https://i.sstatic.net/nuI55.png Here is my existing table: <link href ...

"Using Node.js for proxying requests and implementing OAuth authentication

Having a small node.js application that relies heavily on oAuth, I encountered an issue: the server where I intend to install it is concealed behind a proxy. This necessitates rewriting a portion of the code to incorporate proxy usage. Here's my query ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

I am seeking assistance with my code. It is passing most of the test cases, but is failing only two without any error messages. What could

I recently started teaching myself programming, so please excuse me if my question seems a bit basic. One of the challenges on CodeCamp requires defining a function that takes an array with 2 values as input and returns the Least Common Multiple (LCM) of ...

CSS - Creating a stylish break line for link boxes

Struggling with creating a box that includes linked text and a line break. However, the issue arises when the line breaks, causing the box to also break. After trying multiple options, I still can't seem to find a solution. Check out my attempt her ...

What is the best way to retrieve the file name from the current document's URL using JavaScript?

I need help with a Javascript function that can extract the current file name without any parameters. $(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/); var current_path = RegExp.$1; if ((current_path == 'index. ...

Oops! The regular expression flag "ajax" in Javascript is not valid and is causing

This is my function: public ActionResult RetrieveData(int id) { string name = "Jane"; return Json( new {result=name}); } I'm attempting to fetch information from this function using the code below, but I keep getting errors. Could y ...

Bootstrap 4 content block alignment explained

Below is the code snippet I am currently working with: .banner { background: #f9f9f9; width: 300px; height: 60px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" hre ...

Resend the octet-stream data from an external API

I'm currently facing a challenge with retransmitting data received as octet-stream from an external API in my nodejs application. My previous attempts to convert the API response into a buffer and send it using res.write(buffer(apiResponse.data)) have ...

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

What exactly is the role of the @altfontfamily variable in Bootstrap?

Within the variables.less file, specifically in the typography section, you will find a variable named @altfontfamily. I am interested in utilizing the Alt Font Family but I am unsure of the process. Is there a specific class that needs to be called in or ...

A guide to determining the dimensions (width, height, length) of a mesh using THREE.js

I've been scouring different sources in hopes of finding a way to obtain the width and height of a mesh, but I haven't had any luck. I have imported a collada model into my project, and all I need is to determine its dimensions in Webgl/Three.js ...

Steps to create a floating navbar using tailwindcss

Here is the code snippet for the site header component: export function SiteHeader() { return ( <header className="fixed top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60&qu ...

Refresh a specific portion of an HTML template following a successful AJAX request

I am facing a challenge in implementing a new feature and I'm unsure of the best approach to take. In my project, I utilize Django for backend logic and templating, as well as the Google Closure JavaScript library for frontend development. Here is th ...

How can I create spacing between squares in an HTML div element?

Currently, I am working on my project using Laravel 5. I retrieve some integer values from a database and use them to create square divs in HTML. Below is the current output of my work. https://i.stack.imgur.com/sy2ru.png You may notice that there is spa ...

Setting the z-index for a JavaScript plugin

I need help with embedding the LinkedIn plugin into a website that has stacked images using z-index for layout. I have tried assigning the plugin to a CSS class with a z-index and position properties, but it hasn't worked as expected. Can anyone sugge ...

Show JSON data as choices in a dropdown menu

On my webpage, I want to display a dropdown list populated with objects from a JSON file using JavaScript. Here is the structure of my HTML and JSON: HTML <html> <body> <select id="myid">MyList</select> <script src="m ...

Adjust the translateZ value according to the dynamic height of the element

A unique rotating cube effect has been developed using 3D css transformations. To achieve this, the following transform is applied to a child element: transform: translateY(-50%) translateZ(-75px) rotateX(90deg) ; In addition, the parent element contain ...