Reputation: 3460
I have a 4:3
parent, and a child shrinked and centered. Finally a 4:3
child inside.
.table {
position: relative;
width: 400px;
height: 300px;
border: 1px solid;
}
.top {
position: absolute;
left: 15%;
right: 15%;
top: 20%;
bottom: 20%;
background: yellow;
}
.item {
position: absolute;
width: 10%;
height: 50%;
background: pink;
}
<div class="table">
4:3
<div class="top">
<div class="item">4:3</div>
</div>
</div>
.table
has a 4:3
aspect ratio.top
is distanced by equal amount from the edges of .table.item
should have a 4:3
aspect ratioIn this code .top
is centered and distanced equal from .table
.
Problem is .item
doesn't have 4:3
aspect ratio. (I gave it arbitrary height
, width
). Here's an codepen demo.
Note: .top
is preferred to be distanced equal, it may be close to equal.
Upvotes: 1
Views: 64
Reputation: 103790
You can achieve this with CSS only and the padding-bottom technique to maintain the aspect ratio of the elements. It relies on the fact that percentage padding is calculated according to the with of the container (w3.org reference).
In the following example, I applied the aspect ratio on the .top
element (centered it with absolute positioning and margin:auto;
) this way, you can size .item
with width:100%; height:100%;
as .top
already has a 4:3 aspect ratio:
.table {
position: relative;
border: 1px solid;
width: 400px;
height: 300px;
}
.top {
position: absolute;
width: 70%;
height: 0;
padding-bottom: 52.25%;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
background: yellow;
}
.item {
background: pink;
position: absolute;
width: 100%;
height: 100%;
}
<div class="table">4:3
<div class="top">
<div class="item">4:3</div>
</div>
</div>
This technique also allows you to make the elements responsive by applying the padding technique to the .table
element too:
.table {
position: relative;
border: 1px solid;
width: 30%;
padding-bottom:22.5%;
}
.top {
position: absolute;
width: 70%;
height: 0;
padding-bottom: 52.25%;
left: 0;
right: 0;
bottom: 0;
top: 0;
margin: auto;
background: yellow;
}
.item {
background: pink;
position: absolute;
width: 100%;
height: 100%;
}
<div class="table">4:3
<div class="top">
<div class="item">4:3</div>
</div>
</div>
Upvotes: 1
Reputation: 3931
You could use margin for .top
:
.top {
margin: auto xx auto xx; /* top right bottom left */
}
And then you could set width and height of item:
.item{
height: 200px; /* example */
}
And then you use jQuery to set width:
var cw = $('.item').width();
$('.item').css({'height': 1.2 * cw +'px'});
Upvotes: 0