How come an image with position:absolute doesn't have a height? Even though I can clearly see its height in the browser

I'm perplexed as to why a div with display:block won't position itself below another div with the same style.

Here's my code:

.container{
  display: block;
  position: relative;
}

.container img{
  width: 100%;
  position: absolute;
  top:0;
  left:0;
}

.container .text-left{
  position: absolute;
  top:35rem;
  left:35rem
}

.container .text-right{
  position: absolute;
  top:35rem;
  right:35rem
}
<div class="container" >
  <img src="/image1.jpg" alt="">
  <div class="text_left">
    <h2>HEADING 1</h2>
  </div>
</div>
<div class="container" >
  <img src="/image2.jpg" alt="">
  <div class="text_right">
    <h2>HEADING 2</h2>
  </div>
</div>

I've tried various solutions, like using overflows, but I just can't seem to get the second div with display block to position itself properly below the first.

EDIT: It appears that when using position:absolute elements inside a position:relative element, and that element has a height due to containing an image, the absolute elements remove this height. To fix this, you need to specify the height explicitly.

But why is this happening?

Could it be because of outdated coding practices when using absolute positioning?

Why doesn't the browser take the image height into account by default and only override if necessary?

Can anyone shed some light on this issue for me?

Thanks

Answer №1

The reason for the decrease in height is due to the use of position:absolute;, which removes the element from the normal flow of the document. As a result, the parent container is not able to calculate its height based on that element. This is not an outdated practice, but rather a fundamental aspect of CSS.

For more information, you can visit this article on CSS-Tricks

An important thing to note about absolute positioning is that it removes elements from the flow of the page. Elements with absolute positioning do not interact with other elements and are not affected by them. It is crucial to use absolute positioning judiciously, as improper use can limit the flexibility of your layout.

If you must use position:absolute; for a specific element, one workaround is to adjust the parent container's height using JavaScript/jQuery, though this may not be the most efficient solution.

I recommend attempting to achieve your desired layout without relying on absolute positioning. If you encounter difficulties, feel free to ask for help by explaining your layout goals and sharing your current code.


EDIT

If you are open to using a JavaScript/jQuery solution to adjust the parent container's height based on the image size, you can try the following code snippet:

$('.container').each(function(){
    $(this).css({
        'padding-top': $(this).find('img').height()+'px'
    });
});

This script will add padding to the container based on the image's height. Alternatively, you could insert an empty div below the image and adjust its height accordingly.

Answer №2

To fix the issue, simply change the img and test_* elements' position from absolute to relative. Why? Positioning an element absolutely removes it from the normal flow, causing all the children of your container to also be absolutely positioned, making it seem like the container has no content and collapsing as a result.

.container{
  display: block;
  position: relative;
}

.container img{
  width: 100%;
  position: relative;
  top:0;
  left:0;
}

.container .text_left{
  position: absolute;
  top:90%;
  left:5%;
  color: #fff;
}

.container .text_right{
  position: absolute;
  top:90%;
  right:5%;
  color: #fff;
}
<div class="container" >
  <img src="https://placeimg.com/640/480/any" alt="">
  <div class="text_left">
    <h2>HEADING 1</h2>
  </div>
</div>
<div class="container" >
  <img src="https://placeimg.com/640/480/any" alt="">
  <div class="text_right">
    <h2>HEADING 2</h2>
  </div>
</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

"Experiencing technical difficulties: Website not functioning properly on

I recently created this website. While it functions perfectly on desktop computers, I am encountering issues when trying to access it on mobile or tablet devices. My instinct tells me that the problem may be related to a large css animation on the homepa ...

Issue found in Bootstrap-Multiselect plugin: The dropdown menu appears beneath the outer container when overflow-y is applied

My experience with using Bootstrap-Multiselect and encountering an issue where the dropdown disappears when the outer container has overflow-y: scroll and a max-height has prompted me to seek solutions. I am looking for a way to ensure that the dropdown is ...

Utilizing and incorporating distinct html elements on a separate webpage

I am in the process of developing a dynamic newspaper-style website where articles will be regularly updated and replaced on the Home Page. Each article featured on the Home Page will serve as a link to a separate page for full details. These article links ...

What is the CSS solution for eliminating a line break immediately following the first word?

While designing an email template in html/css for a mailing list, I encountered an issue where on mobile devices the line breaks after the first word for every paragraph. You can see an example of this problem here. The code for the email template was gen ...

When utilizing the ::first-letter pseudo-element on <sub> and <sup> tags

Why is the <sub> and <sup> not supporting the ::first-letter CSS pseudo-element? Any solutions? p:first-letter, sub:first-letter, sup:first-letter { color: red; font-weight: bold; } <p>This text contains <sub>subscript</su ...

Is my website broken due to Internet Explorer?

The progress on my current website project has been smooth so far, but I'm encountering an issue when testing it in Internet Explorer. Whenever I try to view it in IE, the layout breaks completely. You can check it out at . I've attempted using C ...

Is it possible to have a full-width thumbnail navigator in a full-width slider container with Jssor Slider?

I apologize if this topic has already been discussed, In a responsive full-width slider container, I am utilizing thumbnail navigator 03 with the scaling option disabled. Is it feasible to have a fixed-height, but fully (100%) width thumbnail navigator t ...

Ways to consistently return to the main home URL/directory within an HTML document

Greetings to all! Currently facing a challenge with HTML pathing. I want to ensure that every time I log out from Dynamics CRM Portals, I am redirected back to the "SignIn" page. The issue arises when I am in various URLs. For example, logging out from d ...

Guide on eliminating flex in CSS

Having an issue with aligning two grids created in HTML using Bootstrap. Below is the code: <!DOCTYPE html> <html lang="en"> <head> <title>IRIS Flower Classification</title> <link rel="stylesheet" href="{{ url_for( ...

Raise the image above the wrapping div, positioning it at the very bottom

I'm struggling to position an image within a div in a way where: it protrudes above the div it begins at the very bottom of the div (with a small gap that I can't eliminate) Below is the relevant HTML code snippet: <div class="teaser-imag ...

What is the best way to conceal elements that do not have any subsequent elements with a specific class?

Here is the HTML code I have, and I am looking to use jQuery to hide all lsHeader elements that do not have any subsequent elements with the class 'contact'. <div id="B" class="lsHeader">B</div> <div id="contact_1" class="contac ...

Using PHP to access HTML content from a page that demands authentication

I need help developing a PHP script that can scrape data from an HTML page. Right now, it works perfectly with pages that don't require authentication. However, I'm struggling to figure out how to extract content from a page that requires users t ...

How can I display just the time portion of a date in AngularJS?

Hey everyone, I need assistance with displaying only the time value in AngularJS. Check out my Plunker I have fetched the time value using ng-repeat, but I want to display only the time value on my portal. I have tried to display the time value lik ...

"Enhance your website design with a navbar that seamlessly blends with the background color

Question 1: I have a requirement for my navbar to affix overlay on top of the background color and image of the div (top-banner). Currently, when I scroll down, the background color overlays my navbar affix instead. How can I ensure that my navbar sta ...

How can you use the transform property in CSS to rotate the dropdown arrow by 180 degrees and move it vertically by 2 pixels?

gradeexpanded:false, gradeOnClick: function (event) { this.gradeexpanded = !this.gradeexpanded; }, .dropdown-check-list { margin-left: 35px; displa ...

How to stop PHP code from running before it should in an HTML form script

I recently created a form where the PHP code is located directly underneath the HTML form code within the same file. The issue I am encountering is that when the user fails to fill out all required fields and submits the form, the page immediately displa ...

Update the content within an HTML tag using JavaScript

I've been attempting to update the text within the li tag using plain javascript. The structure of the HTML will remain consistent: <section id="sidebar-right" class="sidebar-menu sidebar-right sidebar-open"> <div class="cart-sidebar-wrap" ...

Dynamic drop-down navigation with rearranging menu

I am attempting to design a drop-down navigation bar with 2 rows. Initially, only 1 row is visible. Upon clicking the visible row, both rows should appear. Subsequently, when one of the 2 rows is clicked, only that specific row should be displayed. Below a ...

I find it difficult to customize columns in grid template areas

I am having trouble adjusting the width of my header's columns to be 24vw, 24vw, 4vw, 24vw, and 24vw respectively. Despite specifying these widths, the browser is rendering all columns with equal width. Specifically, I am unable to change the width of ...

Code in JavaScript that shows only a portion of the selected option in a dropdown menu

I'm just starting to learn Javascript and I'm looking to create a script for a select tag that displays countries and their phone codes. My goal is to have the dropdown menu show both the country and code, but once the user selects an option, onl ...