What causes my absolutely positioned element to disappear when using overflow-x: hidden?

I've been experimenting with the CSS property overflow-x: hidden on a container and noticed that it causes my element with position: absolute to disappear.

To see this effect in action, check out this demo: https://codepen.io/Karina1703/pen/LYMzqEj

Take a look at the code below:

.container {
    overflow-x: hidden;  /* Removing this line restores the element visibility */
}

.box {
    position: relative;
    width: 160px;
}

.button {
    width: 100%;
    background-color: blue;
}

.menu {
    position: absolute;
    width: 160px;
    top: 20px; 
    width: 100%;
    background-color: green;
}
<body>
  <div class="container">
    <div class="box">
      <button class="button">Button</button>
      <nav class="menu">
        <div>1</div>
        <div>2</div>
      </nav>
    </div>
  </div>
</body>

Answer №1

The issue arises because the div.container currently has dimensions that match the only relative element inside it, which is the button. As a result, since the navigation is absolutely positioned below the button, it remains hidden from view.

To comprehend the explanation above, it is essential to grasp how position: absolute functions. When an element is set to an absolute position, it is taken out of the normal document flow, and no space is allocated for it in the layout. The element's positioning is with respect to its closest positioned ancestor (if any) or the initial containing block. Its final location is dictated by the values of top, right, bottom, and left.

source

Keeping this in mind, adjusting the heights of both div.container and div.box ensures there is ample space for displaying the inner elements.

This link leads to a visualization of the solution on CodePen.

<html>
    <head>
      <style>
        .container {
            width: 100vh;
            height: 100vh;
            overflow-x: hidden;  /* Removing this line resolves the issue */
        }


        .box {
            position: relative;
            width: 160px;
            height: 100%;
        }


        .button {
            width: 100%;
            background-color: blue;
        }


        .menu {
            position: absolute;
            width: 160px;
            top: 20px; 
            width: 100%;
            background-color: green;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="box">
          <button class="button">Button</button>
          <nav class="menu">
            <div>1</div>
            <div>2</div>
          </nav>
        </div>
      </div>
  </body>
</html>

Answer №2

By using position: absolute, you are indicating that .menu will not affect the layout of its parent container, causing it to have a size of 0. This behavior is explained in the documentation.

If the overflow-x property is set to hidden, scroll, or auto while overflow-y is visible (default), the value for overflow-y will be automatically computed as auto.

The height of the container is calculated based on its elements excluding those with absolute positioning. However, absolutely positioned elements will only be visible within this specific container. To see the effect, try adding top:4px;left:10px; to your .menu CSS rules and it should become visible.

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

New React Component Successfully Imported but Fails to Render

I've encountered issues with the code I'm currently working on. Dependencies: React, Redux, Eslinter, PropTypes, BreadCrumb Within a view page, I am importing components from other files. The current structure is as follows: import Component ...

Exploring the possibilities of page manipulation using React Native WebView

I'm encountering an issue with my implementation of react-native-webview. When I use it to open a webpage, the audio doesn't start playing automatically. Instead, I have to press a button for it to play. Is there a way to make the audio play dire ...

How to properly handle sending an empty post request in Angular 2

My current issue revolves around attempting to send data from my application to the server using a POST request, however, the server seems to be receiving empty POST data. This is the function responsible for sending the data: private headers = new Heade ...

Steps to disable all fields if the previous field is set to its default value and the default value is currently selected

As a newcomer to AngularJS, I have successfully disabled fields based on previous field selections. However, my goal is to set the default value of "ALL" for all fields (country, state, city). If the country value is set to "ALL," then the state and city ...

Troubleshooting a jQuery filter function selector issue

Here's a function I've created: $.fn.filterByClass = function(cls) { var o = $(this); return o.filter(function() { if ($(this).attr("class") == cls) { return $(this); } }); }; Let's say we have multiple fo ...

GetServerSideProps function yielding varied prop values

I'm currently exploring NextJS and delving into SSR. I've been struggling to grasp the functionality of getServerSideProps(). It seems that it should replace useState in order to be rendered on the backend, but I'm receiving different props ...

Encountered an exception while trying to retrieve data with a successful status code of 200

Why is a very simple get() function entering the catch block even when the status code is 200? const { promisify } = require('util'); const { get, post, patch, del } = require('https'); //const [ getPm, postPm, patchPm, deletePm ] = [ ...

The HTML file contains the complete version number of Firefox

If you're an expert in HTML, take a look at my expandable start page. I know there's room for improvement, and I'm seeking advice on automatically updating the Firefox browser version number in line 106 of the code snippet below. (Linux Mint ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

Implementing pagination to streamline search result presentation

I am struggling to implement pagination for the following query that retrieves a lengthy list of items from the database. I want to limit the display to 10 items per page but unsure how to integrate pagination into the existing function. // fetching items ...

Challenges with the Placement of Buttons

I am facing an issue with the code below: document.addEventListener("DOMContentLoaded", function(event) { // Select all the read more buttons and hidden contents const readMoreButtons = document.querySelectorAll(".read-more"); const hiddenConten ...

Access your login page with a nodejs mongoDB connection

After successfully sending username, password, and email through postman, the information gets added to the MongoDB schema. However, on the login page in React, it doesn't seem to work correctly. Any assistance would be greatly appreciated. Thank you. ...

What is the best way to create CSS rules that can be dynamically applied as classes using JavaScript?

I have been attempting to use the addClass function in JavaScript to add a class, but I am struggling to make it work. Is there a specific way to define a class that will be added to an element when clicked on? Here is what I have attempted: var input = ...

Troubleshooting a JavaScript error while attempting to execute a function from a

I have been working on a new JavaScript library named TechX. Check out the code snippet below: (function(){ function tex(s){ return new tex.init(s); }; //initiate the init selector function tex.init = function(s ...

Implementing dynamic database content into a Wow Slider on a jQuery Mobile platform

I am currently using static data in a slider with wow slider jquery mobile. However, I would like to retrieve data from a database and display it in the slider. Can someone provide suggestions on how to do this? Thank you. <script type="text/javascri ...

Transmitting HTML and CSS code to the server for seamless conversion into a PDF file

I recently started using a tool called GemBoxDocument that allows me to convert HTML files into PDFs. Their website provides sample code demonstrating how to convert an existing file on a server (source): using System; using System.Linq; using System.Tex ...

Does a React functional component continuously re-render if it contains a child component?

For the past few days, I've been facing a performance issue in a React app (specifically React Native). The core of the problem is this: Whenever a function component Parent has another function component as its Child, the Parent will consistently re ...

Ways to stop a background image from repeating?

<div style="background-image: url('https://i.ibb.co/v1B855w/bg15.png'); color: #000000; background-color: #000000; background-attachment: fixed; text-align: center;"><img src="https://i.ibb.co/L6zQY0S/name6.png" /> ...

Error: Authentication Error - Headers have already been sent to the client and cannot be modified

I am currently working on handling authentication errors for my website. However, when I submit incorrect data, I encounter the following error: node:internal/errors:478 ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers aft ...

Checkbox does not trigger onCheck event

I am facing an issue with a checkbox component from material-ui where the onCheck event is not firing. <Checkbox label="label" onCheck={onCheck} checked={currentDocument.ispublic} /> function onCheck() { currentDocument.ispublic = !current ...