Drew S Drew S - 5 months ago 12
HTML Question

set css to parent child size

I have the following css and html, and I am trying to get my

<div>
following the
<img>
to inherit the width and height of the
<img>
. The following
<div>
is meant to be an overlay. Is there a way for the
<div>
to obtain the true width and height of the
<img>
?

I have not tried javascript yet and would prefer to do it purely with CSS, but if I must I will use javascript. I am not using jQuery at all and do not plan to.

HTML

<div class="div_1">
<div><img src=""/><div></div></div>
<div><img src=""/><div></div></div>
....
</div>


CSS

.div_1 > div {
float: left;
margin: 8px;
}

.div_1 > div > img {
height: 300px;
width: auto;
}

.div_1 > div > div {
width: .div_1.div.img.width;
height: .div_1.div.img.height;
}

Answer

You can do this by setting to inner div's position to absolute and the outer's to relative:

.div_1 > div {
  float: left;
  margin: 8px;
  position: relative;
}
.div_1 > div > img {
  height: 300px;
  width: auto;
  display: block; /* remove default spacing from bottom of <img> */
}
.div_1 > div > div {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 0, 0, 0.5);
}

/* Not necessary... */

.div_1 > div > div:after {
  content: "Ummmmm, bacon!";
  color: #FFF;
  font-size: 30px;
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="div_1">
  <div>
    <img src="http://baconmockup.com/200/200" />
    <div></div>
  </div>
  <div>
    <img src="http://baconmockup.com/200/200" />
    <div></div>
  </div>
</div>