X Pahadi
X Pahadi

Reputation: 7443

Set child's width to the height of the parent in pure CSS

Can I set the width of a child-div equal to that of it's parent-div height in pure CSS?

JsFiddle Demo

So far, I have been doing in jQuery:

$("#child-div").width($("#child-div").parent().height());

Is this achievable in Pure CSS? For some reasons, I need this to be in Pure CSS. Here's my html:

<div id="parent-div">
    <div id="child-div>Hello</div>
</div>

And CSS:

#parent-div{
    background:#ddd;
    height:80%;
    width:30%; position:absolute;
}

#child-div{
    position:relative;
    background:#333;
    color:#FFF;
    transform: rotate(270deg);
    transform-origin: 0 0 ;
    top:100%;
    height: /* What ???? */;
}

Any tricks?

Upvotes: 2

Views: 2168

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241088

Based on this specific demo, you could use viewport relative units and it will work as expected.

Use width: 80vh in this case - updated example. You can find browser support here.

Since #parent-div has a height of 80% of the viewport, you can use 80vh to set #child-div's width to the same height. This clearly won't work if #parent-div doesn't have a height of 80% of the viewport, though.

As an alternative, you would have to avoid rotating the child element, and just rotate the parent element and give the child element a height of 100%.

Upvotes: 5

Related Questions