Creating a responsive layout that sets the window height to 100% and automatically adjusts sibling divs when the content within parent divs exceeds the defined height

<section>
   <div class="section-wrap">
     <h1>page1</h1>
   </div>
</section> 
<section>
   <div class="section-wrap">
    <h1>page2</h1>
   </div>
</section> 

My attempt at implementing javascript only functions properly when the content of a div is less than the specified height.

 <script type="text/javascript">
    $(function(){
    var windowH = $(window).height();
    var wrapperH = $('section').height();
    if(windowH > wrapperH) {                            
        $('section').css({'height':($(window).height())+'px'});
    }                                                                               
    $(window).resize(function(){
        var windowH = $(window).height();
        var wrapperH = $('section').height();
        var differenceH = windowH - wrapperH;
        var newH = wrapperH + differenceH;
        var truecontentH = $('.section-wrap').height();
        if(windowH > truecontentH) {
            $('section').css('height', (newH)+'px');
        }

    })          
});
    </script>

Answer №1

If you want to ensure that section elements always have a minimum height equal to the viewport size, you can achieve this with the following CSS:

section {
    min-height: 100vh;
}

This technique is widely supported, with even Internet Explorer offering support from version 9 onwards. However, it's worth noting that mobile Safari in iOS 7 may encounter some bugs.

To address any issues with mobile Safari, you can consider using JavaScript. This could involve implementing a polyfill or a workaround like the one below:

jQuery(document).ready(function() {
    jQuery(window).on('resize orientationchange', function() {
        var windowHeight = jQuery(window).height();
        jQuery('section').css('min-height', windowHeight + 'px');
    });
});

Keep in mind that this solution relies on JavaScript and may not work without it. Additionally, it might impose a certain level of computational overhead.

An alternative approach involves integrating specific height rules directly into your CSS:

@media (min-height: 1000px) {
    section {
        min-height: 1000px;
    }
}

@media (min-height: 1010px) {
    section {
        min-height: 1010px;
    }
}

// Similar rules for other heights.

The drawback here lies in the maintenance aspect, as you would need to create numerous rules. To streamline this process, you could utilize a CSS preprocessor like LESS, which allows for a more elegant solution as shown below:

.min-height-100vh(@height) when @height > 0 {
    @media (min-height: @height) {
        min-height: @height;
    }

    .min-height-100vh(@height - 10px);
}

section {
    .min-height-100vh(3000px);
}

By leveraging this method, approximately 300 media queries would be generated. While this may increase stylesheet size and demand additional processing power, it offers a more efficient approach to managing height variations.

Answer №2

Thank you all for your help! I was able to find the solution that worked perfectly on IE8+ and across all browsers, including mobile devices.

html,
body {
  height: 100%;
}
section {
  min-height: 100%;
}
<body>
  <section>
    <h1>section 1</h1>
  </section>
  <section>
    <h1>section 2</h1>
  </section>
</body>

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

How can we improve our vertical division method?

Looking for a more efficient way to create a vertical divider between two divs. I want the divider to be centered between the "why choose" and "gallery" sections. Here is an example of what I'm trying to achieve. I've attempted the following co ...

What is the best way to divide this string with jQuery?

Is there a way to use jQuery to split this specific string? "[10.072721346470422,76.32974624633789][[10.075854059674523,76.32043361663818],[10.073650930297095,76.32888793945312],[10.074918540288232,76.33090496063231],[10.073862198974942,76.33137702941895] ...

Exploring network connectivity using Node.js

As someone who is just starting out with the node super framework, I'm curious to find out if there's a library or sub framework in Node.js that allows users to ping a server from the frontend of a web app. Ideally, this tool would provide variou ...

Retrieving HTML content using scriptJS

Currently utilizing VueJS and encountering an issue after compiling code in production mode. I have one index.html file and several assets that are being uploaded to the cloud. The challenge lies in the fact that the client is not accepting the HTML file ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

Declaring a variable outside of a function or object

It's been a challenge for me to assign a value to the variable result as it always stays undefined. if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } ...

The function is not defined after the button is clicked when an if-else statement is added to the

Hello there, I am currently working on a form to submit data to the database using ajax and CodeIgniter. The form seems to work fine for inserting data, but it lacks validation to check whether the fields are empty or not. I am attempting to add an if-else ...

Customize the look and feel of your website using jQuery's

Is there a way to use an icon from the jQuery Themeroller as a toggle button in a Ruby on Rails project? I want the icon to switch colors when clicked, but I'm not sure how to accomplish this. Any advice on how to achieve this functionality? ...

Can ng-submit be overridden?

Is there a way to modify ng-submit in order to execute certain functions before running the expression it contains? For instance, I want to: 1) Mark all fields as dirty or touched so that validation is performed on all fields, even if the user skipped som ...

Incorporating external script into React website's functional component

I have invested countless hours on this particular issue, which appears to be quite trivial, yet I am unable to pinpoint where my mistake lies. I recently purchased terms and conditions from Termly.com and now wish to showcase these terms and conditions o ...

Displaying the second div once the first div has loaded, then concealing the first div

Current Approach: There are two divs occupying the same space, with div1 set to display:block and div2 set to display:none When a tab is clicked, jQuery hides one div over a period of 2000ms and reveals the other div. Challenge: The goal is for the ...

Unable to forward with POST request in Node.js

I have a button on the front end that allows users to update their profile photo using the Cloudinary API. When the button is clicked, a Node.js POST request is sent with the user's data to query the database and update the profile photo URL. The func ...

The local HTTP server is having trouble establishing a connection with the Firebase user

Utilizing Visual Studio Code editor and a node js HTTP server, I have developed a simple login page and created a user in firebase. However, I encountered an issue with logging in using the username. The code for the webpage was written in HTML and bootstr ...

Create an array of arrays within a loop using TypeScript

My application contains an object with dates and corresponding time arrays. The console log output is displayed below: 32: { 1514160000: Array [ 1200, 1500 ], 1514764800: Array [ 1200, 1500 ], 1515369600: Array [ 1200, 1500 ], 1515974400: Array [ 700, 12 ...

Using PHP, show a specific table row when clicked by matching the ID

I am currently developing an application for a school project that manages tests. This app allows employees to log in, select a client, register clients, and conduct tests with them, all while storing the data in a database. I have successfully implemente ...

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

Best practice for stopping routing in angular

I am currently working on an angular application that includes guest functionality. This feature allows me to create a guest account for all unauthorized users in the background. I need to pause routing until the guest account is created and then specify a ...

Align Text with Icon Using FontAwesome

Hey, I'm having a bit of trouble with something simple and it's driving me crazy. All I want to do is center the text vertically next to a FontAwesome icon. However, no matter what I try, I just can't seem to get it to work. I've looke ...

Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model: var userSchema = new mongoose.Schema( { userName: {type: String, required: true}, firstName: {type: String}, lastName: {type: String}, password: {type: String, required: true}, ...

DreamFactory's REST API POST request for rest/user/session consistently encounters errors in Internet Explorer 9

In Firefox, Chrome, and Safari, the initial POST rest/user/session request works perfectly fine. However, in Internet Explorer 9, it consistently returns an error. When the dataType is specified as "json," IE9 encounters a 'no transport' error w ...