Reputation: 111
How do I make the width and height of a child element the minimum of it's parent's width and height. Just so it can become a square that is contained in its dynamic parent. Something like:
.child{
height: min(parent-height, parent-width);
width: min(parent-height, parent-width);
}
I even tried using css variables like
.parent{
--parent-width: width; /* I also used min-content and max-content */
--parent-height: height; /* also used min-content and max-content */
}
.parent .child{
width: var(--parent-width);
height: var(--parent-height);
}
<!-- The parent of .parent is dynamic -->
<div class="parent" style="width:100%; height:100%;">
<div class="child" style="background:red"></div>
</div>
It didn't word either
Upvotes: 4
Views: 669
Reputation: 886
I didn't find a way how to do it with CSS only. Here is a way it works with CSS + JS.
We get the size of the parent element and a minimum of its width and height. We can do extra calculations with the target value. For example, here we get 80%.
document.addEventListener('DOMContentLoaded', function() {
const element = document.querySelector('.childClass');
const parent = element.parentElement;
function updateSideLength() {
const parentWidth = parent.offsetWidth;
const parentHeight = parent.offsetHeight;
const minSide = Math.min(parentWidth, parentHeight);
document.documentElement.style.setProperty('--side-size', `${minSide * 0.8}px`);
}
updateSideLength();
window.addEventListener('resize', updateSideLength);
});
.parentClass {
background-color: black;
display: flex;
justify-content: center;
align-items: center;
width: 90vw;
height: 90vh;
}
.childClass {
background-color: green;
position: relative;
width: var(--side-size, 0);
height: var(--side-size, 0);
border: 2px solid rgba(0, 255, 0, 0.5);
}
<div class="parentClass">
<div class="childClass"></div>
</div>
Upvotes: 0
Reputation: 841
Plz add this css style..
CSS
.parent{
display:flex;
display:-webkit-flex;
align-items:center;
-webkit-align-items:center;
}
Upvotes: 0
Reputation: 197
.parent
{
background-color:green;
width:300px;
}
.child
{
min-height: 100%;
min-width: 100%;
}
<div class="parent">
<div class="child">Hello, I am Child</div>
</div>
If you set the parent's width and height, the 100% child width and height will be adjusted as per parents width and height.
Upvotes: 1