-1

I need to do something similar to the question

Maintain the aspect ratio of a div with CSS

I have a bootstrap grid of two cells that on mobile goes on a single row each

I would like to insert a box with a fixed proportion of 4:3 and I can't use viewport width and height proportion since the content is already inside bootstrap cell

I would like to know if in CSS3 is possible to express width and height of an element based on his parent width

#box-01,
#box-02 {
  width: 20vw;
  height: 15vw;
  background: gold;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
  <div class="col-sm-6">
    <div id="box-01">4:3</div>
  </div>
  <div class="col-sm-6">
    <div id="box-02">4:3</div>
  </div>
</div>
al404IT
  • 1,380
  • 3
  • 21
  • 54
  • 1
    `I would like to know if in CSS3 is possible to express width and height of an element based on his parent width` . No, i don't think it's possible with just CSS – Mihai T Jan 09 '18 at 17:32

1 Answers1

0

As far as I know, you have one possibility.

Note: Consider this a hack which probably should not be used in production code.

Percentage values of the margin and padding properties are relative to the width of the containing block. This means margin-top and padding-top (running along the Y axis) will respond to changes made to the width of the parent (running along the X axis).

In the following example, .child has a width of 50%, which is relative to the width of the parent. To have its height respond to the width of the parent, we can simulate a height using the padding-top property. Now both the width and the simuated height of .child are relative to the width of .parent, thus preserving the aspect ratio.

(Try resizing .parent to see how .child responds while keeping the aspect ratio.)

.parent {
  width: 200px;
  height: 150px;
  background: orange;
  overflow: scroll;
  resize: both;
  border: 1px solid #999;
}
.child {
  margin: auto;
  width: 50%;
  height: 0;
  padding-top: calc(50% * 0.75);
  background: yellow;
}
<div class="parent">
    <div class="child"></div>
</div>

Now, as anyone will quickly find out, this does not allow for any contents inside .child. To fix this, you can introduce another nested <div> named .grand-child. Make .child relatively positioned and .grand-child absolutely positioned inside of .child.

.parent {
  width: 200px;
  height: 150px;
  background: orange;
  overflow: scroll;
  resize: both;
  border: 1px solid #999;
}
.child {
  position: relative;
  margin: auto;
  width: 50%;
  height: 0;
  padding-top: calc(50% * 0.75);
  background: yellow;
}
.grand-child {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: red;
}
<div class="parent">
    <div class="child">
        <div class="grand-child">
            Hello world
        </div>
    </div>
</div>
agrm
  • 3,735
  • 4
  • 26
  • 36