我正在尝试找到一种方法,使父母div占据了旋转的孩子div的高度
这个问题似乎是在旋转儿童div,但父级div意识到儿童div的非统计高度
我需要红色盒子来覆盖整个绿色钻石。有任何建议吗?
预先感谢您。
https://codepen.io/anon/pen/kowxrb
.parent-container {
position: relative;
background: red;
}
.child-diamond {
position: relative;
width: 500px;
height: 500px;
background: #1eff00;
transform: rotate(-45deg);
transform-origin: 50% 50%;
}
<div class="parent-container">
<div class="child-diamond"></div>
</div>
更新2:感谢Rotem Lurx Horovitz的建议。我添加了其他JS来重新计算DIV,如果用户调整了其浏览器大小。
$(window).resize(function () {
fixDiamondContainerHeight();
});
$(function () {
fixDiamondContainerHeight();
});
function fixDiamondContainerHeight() {
//Calculate the height of the parent div for diamond shape
let $a = $('.child-diamond').width(),
$b = $('.child-diamond').height(),
$c = Math.sqrt((Math.pow($a, 2)) + (Math.pow($b, 2)));
$('.parent-container').height($c);
}
为了最大程度的灵活性(无论绿色方形有多大尺寸( - 使用JavaScript通过像正确的三角形一样看待它,并使用Pythagoras定理来计算新的高度:
如果公式为:a² b²=c²
然后: C =√(A² B²(
然后将parent-container
高度设置为c。
let $a = $('.child-diamond').width(),
$b = $('.child-diamond').height(),
$c = Math.sqrt((Math.pow($a, 2)) + (Math.pow($b, 2)));
$('.parent-container').height($c);
(示例使用jQuery(https://codepen.io/anon/pen/jgbavr
覆盖红色框内的整个绿色盒子。
$(document).ready(function(){
let height = $('.child-diamond').height();
let width = $('.child-diamond').width();
let diagonal = Math.sqrt((Math.pow(height, 2)) + (Math.pow(width, 2)));
let leftPadding = (diagonal - width)/2;
$('.parent-container').css({'height': diagonal, 'padding-left': leftPadding + 'px'});
});
这也可以由CSS完成。
将此添加到您的父级display:table;
.parent-container {
position: relative;
background: red;
display:table
}
示例:https://codepen.io/anon/pen/jgbyav