将孩子的宽度设置为纯CSS中父级的高度 [英] Set child's width to the height of the parent in pure CSS

查看:149
本文介绍了将孩子的宽度设置为纯CSS中父级的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将 child-div 的宽度设置为等于它的 parent-div height 在纯CSS中?


JsFiddle Demo


到目前为止,我一直在做jQuery: / p>

  $(#child-div)。width($(#child-div)。parent()。height ()); 

纯粹的CSS可以实现吗?出于某些原因,我需要这个在纯CSS中。
这是我的html:

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

和CSS:

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

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

任何技巧? p>

解决方案

基于此特定演示,您可以使用 viewport relative units ,它将按预期工作。



使用 width:80vh 在这种情况下 - 更新示例 。你可以找到浏览器支持



由于#parent-div 的高度 80%的视口,您可以使用 80vh 设置#child-div 宽度相同的高度。如果#parent-div 的视口高度不超过 80%,这显然不起作用,作为替代方案,您必须避免旋转子元素,只需旋转父元素并为子元素赋予 > 100%。


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?

解决方案

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%.

这篇关于将孩子的宽度设置为纯CSS中父级的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆