When an absolute positioned element exceeds the right border of its relative parent, its width will be truncated

When position: absolute; divs are placed inside or around a position: relative; parent, their height and width are based on the size and length of the text they contain.

However, if one of these divs extends beyond the right border of the relative parent, its width seems to get truncated.

Is there a way to make the overflowing div behave like the others, using only CSS? (This should be compatible with all major browsers including Edge, but not IE)

Here is the link to the fiddle, and I will also include the code + screenshot below:

HTML:

<div id="relative">
    <div id="absolute-working-left">
        My width and height are determined by my text content.
    </div>
    <div id="absolute-working-middle">
        Mine too.
    </div>
    <div id="absolute-problem">
        Except me... I am having an issue because my width gets cut off when I extend beyond the right side of my 'relative' parent.  WHY???
    </div>
</div>

...and the styles. Please note that I want the maximum width of the absolute div to be 200px before wrapping. Otherwise, the width should be determined by the length of the text:

#relative {
  position: relative;
  width: 100px;
  height: 100px;
  margin-left: 300px;
  background-color: white;
}

#absolute-problem,
#absolute-working-left,
#absolute-working-middle {
  position: absolute;
  top: 45px;
  font-size: 12px;
  max-width: 200px;
}

#absolute-working-left {
  background-color: lightblue;
  left: -300px;
}
#absolute-working-middle {
  background-color: lightgreen;
}
#absolute-problem {
  background-color: red;
  left: 80px;
}

This problem came up while working on a tooltip that needed to be positioned in relation to an offsetParent (or the body if no offsetParent is found in its DOM branch).

Edit: How can this desired behavior be achieved using only CSS?

The solution must be compatible with all major browsers including Edge, excluding IE. It's important to note that the width of the absolute divs cannot be predetermined as it needs to adjust based on the text length... with the exception of a max-width set to 200px in this scenario.

Answer №1

The div named #absolute-issue has a specific left alignment, an automatic width, and an automatic right alignment. As per this guideline in §10.3.7 of the specification, this configuration would lead to the div's width adjusting to fit its content.

If 'width' and 'right' are set as 'auto' while 'left' is not 'auto', then the width adjusts accordingly. Afterward, the calculation for 'right' takes place.

Despite no foolproof method to achieve the desired outcome (due to insufficiently defined properties for width computation), here are several workarounds to address this issue:

Specify a width for the absolute div

An easy fix would be setting a fixed width to prevent shrinking.

#absolute-issue {
  background-color: blue;
  left: 60px;
  width: 120px;
}

[CSS code snippet provided]

Define a right value for the absolute div

In situations where the div's width is unknown, adding a value for right can help adjust the width appropriately.

#absolute-issue {
  background-color: blue;
  right: -60px;
  left: 60px;
}

[CSS code snippet provided]

Utilize fit-content/max-content for the width

Another option involves using either fit-content or max-content (note: limited browser compatibility) instead of setting right. This proves beneficial when the div's content does not span the maximum width.

#absolute-issue {
  background-color: blue;
  right: -60px;
  width: fit-content;
}

[CSS code snippet provided]

Set min-width and max-width

A more practical solution entails allowing the div to resize within a specified range to manage overflow effectively.

#absolute-issue {
  background-color: blue;
  left: 60px;
  min-width: 40px;
  max-width: 160px;
}

[CSS code snippet included]

Answer №2

In a recent project of mine, I came across a similar issue and was able to solve it with a straightforward fix. Simply apply a negative margin-right to the element.

#box-issue {
  margin-right: -8888888px;
}

This approach should resolve the problem effectively. The 8888888px value is set high to ensure that the box extends horizontally based on the content length. Adjusting this value to a more suitable length will provide better control if needed.

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

Exploring the contrast between a hidden element and an element positioned outside the viewport through Selenium testing

When a selenium element is disabled by the ng-show attribute being false, it will have the values Displayed=false and Enabled=true. However, if a selenium element is enabled with the ng-show attribute set to true but is out of the viewport, it will also ha ...

Sending variables to other parts of the application within stateless functional components

My main component is Productos and I also have a child component called EditarProductos. My goal is to pass the producto.id value from Productos to EditarProductos. Here is my Productos component code: import {Button, TableHead, TableRow, TableCell, Tabl ...

Is there a way to access the badge hidden behind the collapsible menu in bootstrap 4?

After moving from bootstrap 3 to bootstrap 4, my items no longer align properly. I've scoured the entire Internet for a solution, but I've run out of options (and patience.. haha) This is how it currently looks: https://i.sstatic.net/ra22j.png ...

Grid element not displaying properly as intended

I'm having trouble centering the content of item in the middle column, it just won't budge. .home-grid-container { display: grid; grid-template-columns: auto; grid-template-rows: 0.10fr 0.98fr auto; height: 100vh; } .home-header { g ...

Cannot access pseudo elements in the Microsoft Edge browser

Is there a workaround for not being able to select or access the properties of :before & :after elements on Microsoft Edge's inspect element? .arrow_box { position: relative; background: #d43959; border: 4px solid #ac1f3c; width ...

Adjust ChartJS yAxes "tick marks"

I'm having trouble adjusting the scales on my yAxes and all the information I find seems to be outdated. My goal is to set my yAxes range from 0 to 100 with steps of 25. Check out this link yAxes: [ { ...

Tips for showing data from Ajax responses on an HTML page

In my code, there are two JavaScript functions: The function fetch_items is responsible for returning data in the form of stringvalue. On the other hand, the function extract_items($arr) passes values to the fetch_items function. function fetch_items ...

Issues with appending new rows using JavaScript

I'm facing an issue with adding rows to the table using this code and I can't seem to find a solution. function add() { document.getElementById("popup").style.display = "block"; document.getElementById("add").addEventListener("click", func ...

Guide on retrieving data from two separate tables within a single database using PHP

I am currently working on a shopping website where I have a table called "products" that stores all the product data. Additionally, there is a separate table named "cart" which contains the products added to the cart, including product ID and user ID. On t ...

Tips on organizing elements

Here are three elements: <!DOCTYPE html> <html lang="en"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.boo ...

Angular Components unexpectedly lose background transparency when using Transparent-Background-PNG in the foreground

Hey there! I'm currently working on a landing page and I have this amazing idea to use a stunning picture of clouds with a transparent background layered over a beautiful landscape. The only problem is that when I try to implement it, the transparency ...

Creating an Innovative Grid Design with Varying Column Widths for Each Row

Seeking advice on achieving a specific layout using HTML. I have attempted to use HTML tables but struggled with creating rows with varying columns. Does anyone have recommendations for grid tools that may be more helpful? Thank you ...

Optimizing the position of smart info windows in Google Maps

I am facing a challenge while attempting to switch the infowindow in Google maps to the smartinfowindow, as the position of the infowindow appears incorrect. This issue only occurs with the smartinfowindow and not with the standard infowindow. Upon furthe ...

Nested divs with independent scrolling capabilities

I am interested in developing a gantt chart that displays days, months, and years at the top with tasks listed below. Here is my progress so far: https://i.stack.imgur.com/tr5y4.png In the image above, the scroll-x functionality works on everything incl ...

What is the purpose of activating hover styles when tapping on mobile devices?

On my button, you can see the color change when hovering: button { background-color: orange; } button:hover { background-color: darkorange; } Check out this example: https://jsfiddle.net/oepb5ks4/ While this works well on desktop, it's a diffe ...

Dynamic resizing of Bootstrap Carousel

As I delve into the realm of web design, I've encountered a puzzling issue with my BootStrap Carousel on a website project. Despite copying the code directly from the BootStrap 5.1 carousel documentation page, its behavior is rather odd, and I'm ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

Gaining a comprehensive understanding of media queries

Hello everyone, I need some help with media queries. I've been working on a website that is already responsive. However, I am required to write the code in a child theme rather than directly in the original files. When I attempt to add new media quer ...

Issue with locating an item in a dropdown menu while using Selenium

I am currently attempting to locate an element within a dropdown list in my Selenium test. Despite identifying the xpath using Firebug, the Selenium code is unable to find it. My goal is to pinpoint option value number 2 in the following html snippet: < ...

Unable to reveal hidden text with invisible formatting (font-size: 0)

I have a Joomla 3 website where I created a blog using a design-controll template. I made a "new-article" page but realized that some buttons were missing text. Upon inspecting with Firebug, I found that there was a font-size:0 property causing this issue. ...