在纯css中设置相对于其父项高度的子项宽度



由于我是网络编程的新手,所以我在css方面还没有获得太多经验。目前,我正在构建一个具有可调整大小标头的web应用程序。因此,我想知道是否可以设置子div的宽度相对于其父div的高度。

我知道如何处理javascript代码中的问题,但我更喜欢纯css解决方案。

css代码看起来像这样:

.parent {
position: relative;
height: 200px;
width: 600px;
}
.parent .resized {
height: 100px;
}
.child {
position: absolute;
height: 20%;
width: 10% [of parent height];
} 

HTML代码如下所示:

<div class="parent">
<div class="child"></div>
</div>

由于父对象的宽度保持不变,因此当前子对象的宽度也保持不变。当父对象的高度调整时,我希望子对象的宽度变小。

提前谢谢。

只需将父元素的高度属性值分配给css变量,然后使用calc()将子元素的宽度分配给父元素高度的10%。

检查并运行下面的代码段,以获取我上面描述的一个实际示例:

.parent {
position: relative;
--parentHeight: 300px;
height: var(--parentHeight);
width: 600px;
background-color: red;
}
.parent .resized {
height: 100px;
}
.child {
position: absolute;
height: 20%;
width: calc(var(--parentHeight) / 10);
background-color: green;
}
<div class="parent">
<div class="child"></div>
</div>

N.B.如果您需要向后兼容IE11,您可以使用polyfill,如另一个SO线程的顶部答案所示。

以%表示的子级宽度和高度会起作用,但它们将使用父级的相应维度来确定。因此,如果子div宽度为10%,则其大小将为父div的10%,如果高度为20%,则子div的高度将为其父div的20%。

您可以在以下示例中看到这种情况:带有边框样式的示例代码,用于区分子div和父div

使用jquery将宽度设置为父高度的10%

如果您想将子div的宽度设置为其父div高度的百分比,那么您将需要jQuery ui方法,如以下示例所示:将宽度调整为父div高度示例的10%。

对于上面的示例,您需要包含jquery、jquery ui和jquery ui css文件;然后只需在父div的jquery对象上调用resizable方法($("parent").rezable()),并在父div停止调整大小时定义一个事件。在这个停止事件中,您可以编写代码,使子div的宽度为父div高度的10%。

您需要理解的主要代码如下所示。在jquery的ready事件中,即当所有dom元素都准备好时,您需要使父div可调整大小,然后为此定义停止调整大小事件。请注意,我正在为父div和子div使用类选择器,即$(".parent") and $(".child")

$(document).ready(function() {
$(".parent").resizable( {
stop : function(e, ui) { 
alert("stopped"); 
//resize the child div now
var childHeight =0.1 *  $(".parent").height();
$(".child").width(childHeight);
} 
});
});

如果你想在你的电脑上玩上面的示例,那么只需使用下面的页面标记/代码。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" 
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css"/>
<style>
.parent {
position: relative;
height: 200px;
width: 600px;
border: 1px solid red;
}
.parent .resized {
height: 100px;
}
.child {
position: absolute;
height: 20%;
width: 10%;
border: 1px solid green;
} 
</style>
<script>
$(document).ready(function() {
$(".parent").draggable().resizable( {
stop: function(e, ui) {
$(".child").width($(".parent").height() * 0.1);
}
}); 
});
</script>
</head>
<body>   
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>

由于父元素是一个固定的高度(在您的示例中为100px或200px),您也可以为子元素制作选择器。

.parent > .child {
position: absolute;
height: 20%;
width: 20px;
}
.resized > .child {
position: absolute;
height: 20%;
width: 10px;
}

最新更新