Attach the element to the bottom of the viewport without obstructing the rest of the page

My challenge is to create a button that sticks to the bottom of the viewport and is wider than its parent element. This image illustrates what I am trying to achieve:

https://i.stack.imgur.com/rJVvJ.png

The issue arises when the viewport height is shorter, as the button ends up covering the content. Here's an example of the problem:

https://i.stack.imgur.com/5dU4V.png

I want the button to remain at the bottom of the content when the viewport is less than the combined width of the button and the content. If I remove the bottom:0 property from the button, it resolves the issue but then the button doesn't stick to the bottom of the viewport for larger viewports:

https://i.stack.imgur.com/XH2ss.png

To ensure the button spans the entire width of both the viewport and its parent element, I have positioned the button absolutely and left the parent element unpositioned. This also prevents me from using flexbox to solve the problem.

Is there a CSS-only solution to achieving this layout, or will I need to resort to using JavaScript?


body {
    box-sizing: border-box;
    height: 100%;
    margin: 0;
    padding: 0;
}
.child {
    background: lightblue;
    text-align: center;
}
.parent {
    overflow: scroll;
    border: 1px solid red;
    height: 100%;
    margin: 0 30px;
}
button {
    border: 1px solid green;
    background: blue;
    color: white;
    width: 100%;
    height: 50px;
    position: absolute; 
    left: 0;
    bottom: 0;
}

Here is the structure of the parent and child elements in the HTML:


<div class="parent">
    <div class="child">
        <!-- Content here -->
    </div>
    <button>button</button>
</div>

https://i.stack.imgur.com/vIur3.png

Answer №1

To address your issue effectively, it seems that utilizing JavaScript is necessary to accurately assess the viewport height versus the child height, enabling you to affix the button at the bottom correctly.

Here is a potential solution:

const windowHeight = window.innerHeight;
const child = document.querySelector('.child');
const button = document.querySelector('button');

function calculateHeight() {
  const childHeight = child && child.offsetHeight;
  // check if total of child's height + button height is less than the viewport height, then fix the button to the bottom
  button.classList.toggle('stick-to-bottom', (childHeight + button.offsetHeight) <= windowHeight);
}


// This section below is for demonstration purposes only, not directly related to the solution
let isOn = true;
button.addEventListener('click', function() {
  let content = 'bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />';
  if (isOn) {
     content = 'bla<br />bla<br />bla<br />bla<br />bla';
  }
  
  child.innerHTML = content;
  isOn = !isOn;
  
  calculateHeight();
});
body {
        box-sizing: border-box;
        height: 100%;
        margin: 0;
        padding: 0;
      }
      .child {
        background: lightblue;
        text-align: center;
      }
      .parent {
        overflow: scroll;
        border: 1px solid red;
        height: 100%;
        margin: 0 30px;
      }
      button {
        border: 1px solid green;
        background: blue;
        color: white;
        width: 100%;
        height: 50px;
        left: 0;
        position: absolute;
      }
      button.stick-to-bottom {
        position: fixed;
        bottom: 0;        
      }
<div class="parent">
      <div class="child">
        bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />
        bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />bla<br />
      </div>
      <button>toggle content</button>
    </div>

Answer №2

If you want to utilize the flex layout mode, there are a few adjustments you can make.

body {
  box-sizing: border-box;
  height: 100%;
  margin: 0;
  padding: 0;
}

.child {
  background: lightblue;
  text-align: center;
  margin: 0 30px;
  border: 1px solid red;
  flex: 1;
}

.parent {
  overflow: scroll;
  height: 100%;
  display: flex;
  flex-flow: column nowrap;
}

button {
  border: 1px solid green;
  background: blue;
  color: white;
  width: 100%;
  height: 50px;
}
<div class="parent">
  <div class="child>
    Updated content goes here...
  </div>
  <button>button</button>
</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

Having trouble locating the search bar element on Walmart's website?

I'm currently working on a bot that needs Selenium to interact with the search bar on Walmart's website, where it will input the name of a specific product and perform a search. However, I've encountered an issue where no matter what method ...

Error encountered in angular.forEach syntax

Can someone help me figure out why my array sum calculation using angular.foreach is resulting in a "syntax error" message? I believe my syntax is correct, as indicated by var sum += value.fare;. Any insights on why this error occurs would be appreciated. ...

Error encountered when attempting to assign a value of the original data type within the Array.reduce function

I am in the process of developing a function that takes a boolean indicator object like this: const fruits = { apple: false, banana: false, orange: false, mango: false, }; Along with an array such as ['apple', 'orange']. The go ...

How can I toggle input disablement in Bootstrap depending on switch selection?

I have been exploring the Bootstrap 5 documentation in search of a way to disable other input fields when a toggle switch input is set to 'off'. The parent element for this scenario is #member_form, and the switch itself is identified as 'to ...

Executing multiple Ajax requests on CodeIgniter 3 from two separate pages

I am facing a critical need for a code review and unfortunately, I am unsure of where else to seek assistance besides here. Let me outline my current task: I am working on a user profile page that is designed to showcase users' comments. Users have t ...

Increase the identification of HTML element with jQuery

I've encountered an issue while trying to increment the id of 2 HTML elements, hwAddition and itemNumber, upon a button click event. The HTML code in question is as follows: <div id="hwAddition"> <div id="itemNumber" s ...

Retrieve the scope object using angular.element and the $ID parameter

In order to transfer data from an angular application to scripts that operate outside of angular, I am seeking a solution since I cannot modify the code of the angular app. By utilizing Angular Batarang and NG-Inspector extensions in Chrome, I have identi ...

Using JQUERY to create a dropdown menu that dynamically changes based on the date field

I am currently working on a JQUERY project and facing a challenging situation. I usually know how to create dropdown menus that depend on one another, but this time I need a dropdown menu that displays age ranges based on the date entered in the birth-date ...

Can you reveal a table with the click of a button?

Hi there! I'm a newcomer to the world of Ruby on Rails and I’m currently working on creating a page that includes a date field. Once a specific date is selected, I’d like to generate a table displaying reports from that chosen date. controllers/r ...

Tips for handling the final row of a CSV file in Node.js with fast-csv before the 'end' event is triggered

After using fast-csv npm, I noticed that in the code provided below, it processes the last row (3rd row) of CSV data only after triggering the "end" event. How can this issue be resolved? ORIGINAL OUTPUT : here processing request here processing re ...

Hiding a pop-up element and updating the state to False when clicking anywhere outside the element in the background

Presented here is my Search.js component. class Search extends Component { state = { doctors: [], showTab: false } openTab = () => { this.setState({showTab: true}); console.log('openTab state', this ...

The jQuery functions are unable to function properly when retrieving AJAX data

I am currently working on a script that inserts a record into my database using AJAX. After inserting the data, it is posted back in the following format... Print "<li>"; Print "<span class='cost'>" . $bill. "</span> "; Print ...

Storing deeply nested arrays of objects with Mongoose leads to MongoDB storing empty objects

Here's the issue I'm facing: I am trying to save nested objects with mongoose in mongodb, but when I save them, the nested objects end up empty. I have attempted various solutions found online, such as pushing objects and populating, but none o ...

Using orchestrate.js for local passport.js authentication

I need assistance finding a tutorial or resources for setting up local passport.js authentication with Orchestrate as the user storage. Most of the resources I have come across are based on MongoDB, but our project requires us to use Orchestrate. Any advic ...

Every time I attempt to create a detail page for a table, I am consistently greeted with an error message

Error: Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /var/www/2909kher/entabell/detaljer.php on line 23 <!doctype ...

What is the best method for performing cross-domain queries utilizing ajax and jsonp?

When attempting to send an ajax request to a specific URL, I encountered an error. Below is the code I used: $.ajax({ url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n", dataType : 'jsonp', ...

Update the state when a button is clicked and send a request using Axios

Currently in my front end (using react): import '../styles/TourPage.css'; import React, { Component } from 'react'; import axios from 'axios' class TourPage extends Component { constructor(props) { super(p ...

Attempting to position items within a container

Currently, I am in the process of creating a list of job opportunities to be displayed on a side bar of our careers page. Each job listing should include the job title along with an apply button enclosed within a rounded grey box that allows for some spaci ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

Navigating a JSON message received from a websocket: Best practices

How can I cycle through various types of JSON messages received from WebSocket and trigger a function based on the type to modify observables in MobX? Can anyone assist with this? For instance, one of the simple messages looks like this: { name: "as ...