Positioning images within a relatively positioned div using absolute positioning

I have come across multiple discussions on this topic, but I am still struggling to make the following code snippet function correctly:

.container {
  position: relative;
  width: 100%;
}

.left {
  position: absolute;
  left: 0px;
}

.right {
  position: absolute;
  right: 0px;
}
<html>

<body>
  <div class="container">
    <img src="..." class="left" />
    <img src="..." class="right" />
  </div>
</body>

</html>

After referring to information available at http://www.w3schools.com/css/css_positioning.asp, especially the statement that reads as follows:

An absolute positioned element is located in relation to the first parent element that has a position other than static. In case there are no such elements found, the containing block defaults to <html>

The main problem lies in the fact that the container div lacks any height. I would prefer not to specify the height of the container div. Although I am aware that floating one image to the left and another to the right, along with applying overflow: auto to the container div can resolve the issue, I was hoping to avoid that approach as I appreciate the technique of utilizing absolute positioning within a relative div.

Is there a possibility of achieving this without those alterations?

Answer №1

It's not possible for the parent container to automatically adjust its size based on absolutely positioned children because those children are not within the flow of the document.

The most effective approach for achieving what you want is to utilize floats along with a clearfix method:

body {
  padding: 20px;
}

.container {
  position: relative;
  width: 100%;
  background: yellow;
}

.left {
  float: left;
  background: red;
  width: 100px;
  height: 200px;
}

.right {
  float: right;
  background: blue;
  width: 100px;
  height: 200px;
}


/* Use the clearfix technique: http://www.yuiblog.com/blog/2010/09/27/clearfix-reloaded-   
    overflowhidden-demystified/ */

.clearfix:before,
.clearfix:after {
  content: ".";
  display: block;
  height: 0;
  overflow: hidden;
}

.clearfix:after {
  clear: both;
}

.clearfix {
  zoom: 1;
}


/* IE < 8 */
<body>
  <div class="container clearfix">
    <div class="left">
      Left
    </div>
    <div class="right">
      Right
    </div>
  </div>
</body>

If you really need to use absolute positioning and require the parent container to match the height of the children, JavaScript will be necessary for achieving that functionality.

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

Python: parsing comments in a cascading style sheet document

I am currently working on extracting the first comment block from a CSS file. Specifically, I am looking for comments that follow this pattern: /* author : name uri : link etc */ and I want to exclude any other comments present in the file, such as: /* ...

How can I make the scrollbar invisible in the sticky header of a Material UI Table?

In my React project, I have implemented a Material-UI Table with a fixed header. The issue I am facing is that the scrollbar in the table header overlaps it and I want to hide it while still displaying it in the body of the table. I have attempted to modi ...

Show the image on top of the div block as the AJAX content loads

Implementing this task may seem easy and common, but I am struggling to figure it out! What should take five minutes has turned into an hour of frustration. Please lend me your expertise in getting this done. I have a div container block: <div cla ...

A comprehensive guide to navigating pages using AngularJS

Greetings! I've recently embarked on my Angular JS learning journey and have encountered an issue with loading content from pages. Unfortunately, I am not able to receive any content. Below are snippets of my index file and corresponding JavaScript co ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

How can I use jQuery to set the color of every other row in a

I'm facing an issue where I want to use jQuery to set the color of alternate rows in an HTML table. However, every time I add a new row, the color of the entire table switches. Below is the JavaScript code snippet that I am utilizing: var alternate = ...

Adding dynamic elements to a pop-up window with the use of jQuery's .load() function

When implementing Javascript to create a modal, I have encountered an issue where the close button disappears. The modal opens and loads different HTML files dynamically using the jQuery load() method, but the close button vanishes. I suspect that the mod ...

Setting the borderRadius for a web view on Android Maps V3: A complete guide

In my application, I am using Android Map V3 and have encountered a bug specific to the Kit-Kat version. The chromium kit throws up an error message - nativeOnDraw failed; clearing to background color, which prevents the map from being displayed. Despite ...

Is there a way to prevent the text in my text boxes from staying there when I refresh the page?

Currently working on an HTML5 project with Javascript, here is a snippet of my code: Your inquiry <textarea type="text" name="phrase" id="phrase" cols="50" rows="5" placeholder="Write your text here. . ."></textarea> I am looking for a way ...

Can Webpack be used to produce only CSS files without generating the output.js file?

I've integrated Webpack into my project alongside the extract-text-webpack-plugin. Within my project, I have various build scripts. One of these scripts focuses solely on bundling and minifying CSS. While utilizing Webpack for other tasks, I decided ...

Looking for guidance on managing view redirection in Django (Updated)

I ran into an issue with a previous question I posted, you can find it here Due to some formatting errors because it was my first time posting a question, the original question is currently closed. I have made edits and resubmitted it for reopening, but I ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

Implement a JavaScript and jQuery code that alternates between fading in and fading out every two items in a

Can someone help me figure out how to create a loop that fades in and out every 2 items from an unordered list using jQuery? I've been trying to do this, but my loop only processes one item at a time. <div> <ul> <li>item1</li ...

Display HTML elements that are specifically <p> nodes

I am currently experimenting with HTMLParser to extract and print only the contents enclosed in "p" tags from an HTML document, excluding any other content within different types of tags. from HTMLParser import HTMLParser class MyHTMLParser(HTMLParser): ...

Experiencing an issue where the canvas element fails to render on mobile Chrome browser,

I've encountered an issue with a script that draws a canvas based on the background color of an image. The image is loaded dynamically from a database using PHP. The responsive functionality works fine on mobile Safari, but not on Chrome. When the re ...

Navigate to the following section on an HTML page by clicking a button using jQuery

Within my application using Jquery / Javascript, I am looking to implement a specific functionality. I currently have several div elements like the ones below: <div id="div1"></div> <div id="div2"></div> <div id="div3"></ ...

Having trouble retrieving cell values from a table using tr and td tags in C# Selenium is causing issues

I'm facing an issue where my code is unable to retrieve the cell value and instead throws an exception stating: "no such element: Unable to locate element: {"method":"xpath","selector":"html/body/div[2]/div[2]/table/tr[1]/td[0]}" Below is the HTML ma ...

The required keys [:id] are not included in the route matches

As a beginner in Rails, I've encountered similar issues that I can't seem to resolve. Here are my routes: resources :users do resources :items end My model setup is as follows: class Item < ActiveRecord::Base belongs_to :user end cl ...

Tips for adjusting the positioning of a div element in a responsive design

I am currently working on my website and facing a layout issue. In desktop mode, there is a sidebar, but in mobile view, the sidebar goes down under the content displayed on the left side. I would like the sidebar to appear at the top in mobile view, fol ...

Creating a pull-up toolbar with just HTML and CSS for an Android browser

I need to create a draggable toolbar on my mobile webapp that can reveal content beneath it. I want to achieve this using just HTML/CSS, without relying on touch/scroll events or libraries. To do this, I'm overlaying a scrolling element on top of the ...