Create a div element that is positioned absolutely and is able to be scrolled

Struggling to create a chat HTML template that allows for a scrollable message area? Let me break down the structure:

Chat header: Title or name at the top.
Message input box: Write messages here.
Visible chat area: Height of container minus (header height + input box height).
Messages display: Automatically adjust in height but always stay at the bottom for latest message.

This setup coexists with other HTML elements, not full screen.

https://i.sstatic.net/4FrnY.jpg

The HTML structure:

<div id="chat-1" class="chat-window">
    <div class="chat-header">
        <h4>Header</h4>
    </div>
    <div class="message-container">
        <div class="general-message-container">
            <div class="message-wrapper">
                <!-- messages content -->
            </div>
        </div>
    </div>
    <div class="text-area">
        <textarea class="form-control" placeholder="Type your message"></textarea>
        <a href="#" class="send-message"></a>
    </div>
</div>

CSS styling:

.chat-container {
  height: 70vh;
  min-height: 400px;
}

.chat-window {
  position: relative;
  display: inline-block;
  width: 65%;
  float: left;
}

.chat-window, .message-container {
  height: 100%;
}

.message-container, .general-message-container {
  padding: 15px 15px 20px 15px;
}

.chat-header {
  z-index: 1;
  position: absolute;
  top: 0;
  left: 0;
}

.message-container {
  position: relative;
  overflow-x: hidden;
  overflow-y: scroll;
  height: 400px;
}

.general-message-container {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}

.chat-window, .message-container {
  height: 100%;
}

.message-container {
  height: calc(100% - 46px);
}

.message-container, .general-message-container {
  padding: 66px 20px 25px 20px;
}

.text-area {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}
.text-area .form-control {
  resize: none;
  height: 46px;
  padding: 10px 20px;
}

If setting .general-message-container to position: relative; makes it scrollable but you can't align it to the bottom, try...

Answer №1

It seems like I understand what you're looking for.

Although it may be obvious, if JavaScript is allowed we can use a bit of it (jQuery in this case) to achieve the same result:

[JSFIDDLE]

function returnScrollHeight() {
    return this.scrollHeight;
}

$('.chat-mensajes-contenedor').scrollTop(returnScrollHeight);

$('textarea.form-control').on('keyup', function (e) {
      if (e.ctrlKey && e.keyCode === 13) {
        $('.mensaje-contenedor').append('<div class="line">' + this.value + '</div>');

        $('.chat-mensajes-contenedor').scrollTop(returnScrollHeight);

        this.value = '';
    }
});

I couldn't find a solution without JS quickly. Hopefully someone else will provide an HTML/CSS only answer soon.

Answer №2

Check out this demonstration on a fiddle: https://jsfiddle.net/gLahjk5z/3/

I made adjustments to the position styles by setting them to position: relative and made changes to some height attributes.

In addition, I included a JQuery function that will execute when the document is ready:

$(document).ready(function() {
    var bottom = $(".mensaje-contenedor").height();
    $(".chat-mensajes-contenedor").scrollTop(bottom);
})

To ensure that messages always display at the bottom, apply the following CSS:

.chat-mensajes-contenedor-general {
    min-height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.mensaje-contenedor {
    align-self: flex-end;
}

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

Utilizing the sAjaxSource property in Datatables to fetch data through Ajax from multiple tables while dynamically passing arguments

I am facing an issue with populating two datatables using data retrieved from a flask API through a GET request. My data source URL is localhost:5000/data, but for some reason, I am unable to display the data in the datatables. Interestingly, when I use a ...

Tips for repositioning the navbar toggle button and logo to the left using Bootstrap

Is there a way to relocate the navbar toggle button and logo to the left side of the page using Bootstrap?https://i.sstatic.net/4gKRl.png ...

The bxSlider reloadSlider() function is not defined once the page has finished loading

I am currently working on developing an interactive upload and refresh gallery using AJAX and jQuery. The application allows for the upload of multiple images through drag & drop. After uploading, I need to visualize how the new gallery will appear with t ...

Creating the Perfect Layout: Unveiling the Secrets of Bootstrap 4

Currently in the process of working on a website, I have encountered a particular challenge regarding the layout design using Bootstrap 4. (Highlighted in Red) https://i.sstatic.net/k8bKv.png The issue at hand is that the first column is a col-md-7 and t ...

Can the AJAX response be utilized for FullCalendar events?

I currently have the following code snippet in my event dropdown: $.ajax({ type: "POST", url: "CalendarServices.aspx/UpdateDrop", data: 'id=' + event.realid + '&start=' + $.fullCalendar.formatDate(event.start, 'yyy ...

The React input field seems to be unresponsive to updates

I'm working on a React/Next application where users can create and update notes/jobs. However, I am facing an issue with my onChange={handleChange} function when trying to edit the input fields. Can anyone point out what might be going wrong? Thank y ...

Steps for establishing a secure anchor point

Trying to set an anchor point has been a bit challenging. I attempted using: <a href="index-xxx.html#reference-name"> and <a name="reference-name"> The issue is that there is a floating margin on the top, causing the anchor point to go to th ...

Is there a way to include core modules in my package.json dependencies in Express in order to utilize them in my JavaScript files?

I'm currently exploring the 'connect' core module, and my understanding is that express utilizes this module internally. I'm attempting to manually require it, but I seem to be encountering issues with installation using git bash. Below ...

The query parameter is not defined in the router of my Next.js app API

I'm currently working on building an API endpoint for making DELETE requests to remove albums from a user's document in the MongoDB Atlas database. Struggling with an error that keeps popping up, indicating that the albumName property is undefin ...

Discovering the method to retrieve the values from 2 dropdown lists that are populated by a JavaScript function

I have a pair of dropdown lists in a JSP file labeled 'speciality' and 'super_speciality'. Clicking on an option in the 'speciality' dropdown list dynamically populates options in the 'super_speciality' dropdown list ...

Tips for implementing personalized/modified CSS on Vuetify components?

Let's say I've included the v-text-field component from Vuetify in my Vue component as shown below: <v-text-field v-model="email" name="email" type="email" color="#90C143" label="Email"> Upon inspecting the element, it generates regular H ...

Create an interactive JSON tree structure

I am looking to create a JSON tree from an array. My array is structured like this: var arraySource = []; arraySource.push({key : "fr", value: "france"}); arraySource.push({key : "es", value: "spain"}); //... console.debug(arraySource); The desired JSON ...

A full-width CSS menu featuring dropdowns beneath each entry for easy navigation

Check out the JSFiddle here I've created a full-width CSS menu that spans the entire screen, but I'm struggling to figure out how to make the corresponding subnav items appear below their parent items. Is it even possible to achieve this design ...

The Safari browser is unable to provide the country name in the geolocation response

My geolocation feature for displaying country names is functional in Chrome and Firefox, but not in Safari. How can I troubleshoot this issue? Javascript: $.get("http://freegeoip.net/json/", function (response) { $("#ip").html("IP: " + response.ip); ...

Tips on creating a personalized memoizeOne function that delivers the accurate data type

I've implemented a function for object memoization: import memoizeOne from 'memoize-one'; type ArrayWithOneObj = [Record<string, unknown>]; const compareObject = ([obj1]: ArrayWithOneObj, [obj2]: ArrayWithOneObj) => obj1 === obj ...

Tips for preventing redundant HTTPInterceptor requests when transitioning between RxJS mergeMap operations

My system utilizes two JWT tokens: a Refresh Token (expires after 7 days) and an Access Token (expires after 15 minutes). These tokens are securely stored on httpOnly cookies and can be accessed via the server. The refresh method generates a new token and ...

Unable to successfully scroll a webpage using Selenium Webdriver or Javascript Executor

`from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains import time driver = webdriver.Chrome('chromedriver.exe' ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...

Ordering results based on function output within a v-for loop in Vue.js

In my code, I have an array that I am looping through in the following way: <template v-for="plan in plans"> ... </template> My goal is to sort the plans array by a calculation based on certain properties of each plan. Let's ...

JavaScript causing Selenium/Beautiful Soup scraper to crash after parsing only one page

As I try to scrape data on food seasonality from the Seasonal Food Guide, I've encountered a roadblock. The URL structure of the website is quite simple: Using Selenium and Beautiful Soup, I've managed to successfully extract seasonality informa ...