Home > Mobile >  Div with default width when empty and adjust to smaller content when its present
Div with default width when empty and adjust to smaller content when its present

Time:07-13

I have a div that can have an image inside of it, but it can be empty as well. The div must have a minimum width of 400px when it is empty, but if i add an image of smaller width inside, like 200px, the div should adjust accordingly.

So the div's behaviour would be as if the min-width was less than the image width. Also, it should adjust normally if the image's width is greater

Here is what i have so far

Div in black with min-width greater than image's width

What i want to achieve

Outside div adjusted to content's smaller width

And here is the code

<div style="min-width: 400px; height: 200px;">
  <img src="test.png" style="height: 100%; max-width: 100%; display: inline-block;">
</div>

How can it be achieved with only CSS and HTML?

CodePudding user response:

You can use JavaScript

const container = document.querySelector(".container");
const img = new Image();
img.addEventListener("load",function() {
  container.innerHTML = `<img src="${img.src}" />`
  container.style.minWidth = `${img.width}px`;
}) 
img.src = `https://media4.giphy.com/media/3oEjI5VtIhHvK37WYo/giphy.gif?cid=ecf05e47ttcotdceltg5awcdfpqk4mc1mr65aogmhqzga0xl&rid=giphy.gif&ct=g`
.container {
  padding: 5px;
  border: 1px solid black;
  width: fit-content;
  min-width: 400px;
}
<div ></div>

CodePudding user response:

A has pseudo-class can select parent elements based on the elements inside. Combining it with the not pseudo-selector should achieve exactly what you want. Unfourtanetly, it is not supported almost by any browser, so I guess you'll have to use JavaScript for that. I don't know another way to achieve that by HTML & CSS only.

.container {
  padding: 5px;
  border: 1px solid black;
  width: fit-content;
}

.container:not(:has(>img)) {
  min-width: 400px;
}
<div ></div>
<div >
  <img width="200" src="https://media4.giphy.com/media/3oEjI5VtIhHvK37WYo/giphy.gif?cid=ecf05e47ttcotdceltg5awcdfpqk4mc1mr65aogmhqzga0xl&rid=giphy.gif&ct=g" />
</div>

A JavaScript solution may be something similar to that.

// find all the containers
const containers = document.querySelectorAll('.container');

// loop through each of them
for (const container of containers) {
  // check if the container contains an image
  const hasImage = !!container.querySelector('img');
  
  // if it doesn't, apply a min-width of 400px to it.
  // you can replace it with container.classList.add('class-name') to use CSS classes for that.
  if (!hasImage) container.style.minWidth = '400px';
}
.container {
  padding: 5px;
  border: 1px solid black;
  width: fit-content;
}
<div ></div>
<div >
  <img width="200" src="https://media4.giphy.com/media/3oEjI5VtIhHvK37WYo/giphy.gif?cid=ecf05e47ttcotdceltg5awcdfpqk4mc1mr65aogmhqzga0xl&rid=giphy.gif&ct=g" />
</div>

  • Related