I have a div with this css rule:
.somediv {
aspect-ratio: 1 / 3 !important;
}
I want to make the height equal not exactly (3 * width), but plus 8 pixels. For example, if my width is 10px, the height have to be like (10*3) 8 = 38 pixels. How can i do this, i know about calc() in css, but not sure it works with aspect-ratio.
CodePudding user response:
If you are to set a fixed width , you may use CSS var() to set the width, then use calc() for aspect-ratio
examples
:root {
--width: 80;
}
div {
margin: 1em;
border: solid;
width: calc(var(--width) * 1px);
aspect-ratio: var(--width) / calc(var(--width) * 3 8);
/* demo purpose */
float: left;
}
div:before{
content:attr(style);
<div>défault</div>
<div style="--width:100"> </div>
<div style="--width:101"> </div>
<div style="--width:70"> </div>
<div style="--width:90"> </div>
If width is not, then javascriipt will be required
CodePudding user response:
You can add a padding-top
on the element you are styling for its size. It's counter intuitive because the size is supposedly ruled by the element width
and its aspect-ratio
but as you can see here in this demo, I show the computed width and height of the elements inside an ::after
pseudo element through a data attribute I set via javascript with the actual offsetWidth
and offsetHeight
.
Given the width
as 100px
the height is indeed width*3 8px = 308px
const target = document.querySelector('div');
target.dataset['width'] = `${target.offsetWidth}px*${target.offsetHeight}px`;
.width-100{
width: 100px;
}
.ratio-1over3 {
aspect-ratio: 1 / 3;
padding-top: 8px;
}
.outline{
outline: solid red;
}
.ratio-1over3::after {
content: attr(data-width);
display: block;
}
<div >
</div>
CodePudding user response:
You could use two <div>
, a parent, with the dimensions and the aspect ratio, and a child with the calc()
:
.somediv {
width: 100%; /* or any width you want */
height: auto;
aspect-ratio: 1 / 3 !important;
}
.somediv__inner {
width: 100%;
height: calc(100% 8px);
background: blue;
}
<div >
<div ></div>
</div>