Tips for sizing a div based on the dimensions of an image

Looking to Achieve:

I have a PNG image of a shirt with a transparent background that I want to place on top of a colored square. I want the shirt in the image to stand out over the edges of the square, creating a visually appealing effect. The image's width is set to 100%, and the height adjusts automatically to maintain the original aspect ratio. When the window is resized, the square's height and width should adjust in relation to the image's dimensions, ensuring a responsive design.

Previous Attempts:

I attempted to use a div for the colored square and an img HTML element for the image, placing both elements within a container:

Here is the CSS for the square:

.square {
    width: 80%;
    height: 80%;
    margin-left: auto;
    margin-right: auto;
    margin-top: 10%;
    background-color: red;
    z-index: -1;
}

CSS for the image:

.shirtImage {
    width: 100%;
    margin-left: auto;
    margin-right: auto;
}

The container is simply a div.

The Issue:

The problem I encountered was that the 80% height set for the square was relative to the entire page, extending to the bottom, instead of just being contained within the div wrapping the image and square. I understand that this method is flawed because I expected the square to derive its height from the parent div (wrapping div), which in turn should adjust based on the child image's height. I'm struggling to understand why it's not working and how to resolve this issue.

Answer №1

To create a square div, use a pseudo element to make the div the parent and then apply vertical padding or margin to stretch it into a square shape. To insert an image without affecting the height of the div, position it absolutely within the parent.

https://developer.mozilla.org/en-US/docs/Web/CSS/padding

<percentage>

The size of the padding as a percentage, relative to the width of the containing block.

Here is a potential example:

.square {
  width: 80%;
  height: 80%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 10%;
  background-color: red;
  z-index: -1;
  position: relative;
  overflow: hidden;
}

.square:before {
  content: '';
  display: block;
  padding-top: 100%;/* equals width of parent */
}

.shirtImage {
  width: 95%;/* 95 instead 100 for the demo*/
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom:0;
  right:0;
}
<div class="square">
    <img class="shirtImage" src="http://dummyimage.com/100/fe0">
</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

Python regular expressions: eliminate specific HTML elements and their inner content

If I have a section of text that includes the following: <p><span class=love><p>miracle</p>...</span></p><br>love</br> And I need to eliminate the part: <span class=love><p>miracle</p>.. ...

Navigating to an offline HTML webpage using JavaScript in a PhoneGap application

I am currently developing a phonegap application. I am attempting to create a login feature where upon clicking the submit button on the Login.html page, I should be directed to a local HTML file. Login.html <tr> <td>&nbsp;</td> ...

Having trouble displaying the fancybox helper buttons

I had everything working perfectly, but suddenly it stopped and I can't figure out what went wrong. I just need the left, right arrows, and helper buttons to appear when fancybox is open. Any assistance would be greatly appreciated. PS: All the neces ...

Steps to ensure your Bootstrap side menu spans the entire height of the page

Welcome to my side menu <template> <div class="p-3 text-bg-dark shadow"> <div class="dropdown"> <a href="#" class=" align-items-center text-white text-d ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

Is it recommended to place JavaScript/CSS at the bottom of an HTML document?

I am currently utilizing jQuery Mobile, and at the moment, my <head> section looks like this: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <title>help</title> <link ...

What is the best way to create a mirror effect on one div by clicking another div?

I have created a schedule grid and I am looking for a way to allow users to click on the UK hour and then have the corresponding U.S time highlighted. Is there a CSS solution for this? The functionality I need is to be able to select multiple hours. I have ...

`The LiipImagineBundle HTML encoding error`

Utilizing LiipImagineBundle, I efficiently resize my images after uploading. However, I encountered an error specifically when trying to upload certain JPEG files due to HTML encoding issues. The resizing process works fine with JPEG files from my camera, ...

How to Incorporate Multiple React Components in an HTML File

Attempting to integrate React code into an HTML file has been a challenging process for me. I've been following the official React documentation and successfully implemented their basic like button starter code on my page. Initially, everything worked ...

Ways to determine if the user is using a mobile device with CSS

Is there a way to detect mobile users using CSS? I am working on a project that requires detecting mobile users, but I am unsure how to do so. Can you provide any guidance? ...

Place an element in the middle of the svg

I have a D3.js svg element measuring (1000,1000) with a circle positioned randomly, such as (100,200). My goal is to adjust the svg so that the circle is centered at (500,500). I want to create a function that can do this for any randomly positioned circl ...

Angularjs directive retrieves infowindow DOM element from Google Maps

In order to apply some style fixes to the Infowindow, I am trying to select the element with the class 'gm-style-iw'. This selection process is taking place within an angularjs directive. <div ui-view="full-map" id="full-map" class="mainMap c ...

Strange occurrences with the IMG tag

There seems to be an issue with my IMG element on the webpage. Even though I have set the height and width to 100%, there is some extra space at the end of the image. You can view the problem here: I have also included a screenshot from the developer too ...

Consolidate duplicate list entries and adjust the CSS as needed

Imagine I have an array like this: myarray = ["apple", "apple", "apple", "potato", "apple"]; myarray = ["apple", "apple", "apple", "potato", "apple"]; function listCreate(data) { var output = '<ul>'; $.each ...

Having issues with the sidebar malfunctioning and unsure of the cause

<html> <head> <title></title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> I've been working on creating a sidebar for my website, but it's not functioning as expect ...

Execute a JavaScript function when an HTML list element is clicked

As a beginner in web development, I have a question that might seem obvious to some. I want to create a menu where each item, when clicked, triggers a JavaScript function with the item's ID as an argument. I plan to display the menu items in an unorde ...

Ways to eliminate the Horizontal scroll bar

Currently, I am in the process of transforming a Static Page into a Responsive Page. However, when I resize my page to a lower width, I notice that a horizontal scroll-bar appears along with some margins at the bottom and right side of the last div/Footer. ...

Changing button alignment using CSS to create a new line

Currently, I am working on a React project using Material-UI where I am trying to create a numpad. The code snippet below showcases part of my implementation: // some parts are omitted for conciseness const keys = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0]; ...

What is the method for passing an element in Angular2 Typescript binding?

Is there a way to retrieve the specific HTML dom element passed through a binding in Angular? I'm having trouble figuring it out, so here is the relevant code snippet: donut-chart.html <div class="donut-chart" (donut)="$element"> ...

Resolving VSCode WebViewPanel access issues through a corporate proxy

I am currently utilizing the "C4 DSL Extension" in VSCode to display previews of my architecture diagrams. These previews are generated through the WebviewPanel functionality. If you're interested, you can access the source code here: While everythin ...