Home > Web Front-end > CSS Tutorial > How Can I Make a Parent Div Expand to Accommodate an Absolutely Positioned Child?

How Can I Make a Parent Div Expand to Accommodate an Absolutely Positioned Child?

Patricia Arquette
Release: 2024-12-27 10:09:14
Original
582 people have browsed it

How Can I Make a Parent Div Expand to Accommodate an Absolutely Positioned Child?

Parent Div Expansion with Absolute Positioned Child

When working with CSS, sometimes it's necessary to position an element before another on both desktop and mobile devices. However, absolute positioning removes elements from the flow, making them ignored by other elements.

In this scenario, consider the following HTML and CSS:

<div>
Copy after login
parent {
    position: relative;
    width: 100%;
}

child1 {
    width: auto;
    margin-left: 160px;
}

child2 {
    width: 145px;
    position: absolute;
    top: 0px;
    bottom: 0px;
}
Copy after login

With this setup, child2 is intended to be positioned before child1. However, this configuration fails because child2 is removed from the flow, causing the parent div to ignore its height. Attempts to set overflow:hidden or use clearfix on the parent have no effect.

The fundamental issue is that absolute positioned elements are not considered in the height calculation of their parent containers. Therefore, it's not possible to determine the height of the parent based on an absolutely positioned child.

To address this issue, two options are available:

  • Use Fixed Heights: Assign fixed heights to both child1 and child2, ensuring that the parent div's height is sufficient to accommodate both.
  • Involve JavaScript: Use JavaScript to reposition the two divs dynamically, maintaining the desired visual order and ensuring the parent div's height adjusts accordingly.

The above is the detailed content of How Can I Make a Parent Div Expand to Accommodate an Absolutely Positioned Child?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template