如何仅使用CSS获得元素的高度

问题描述 投票:18回答:2

我们有很多选择可以使用jQuery和JavaScript来获取元素的高度。

但是我们如何仅使用CSS来获得高度?

假设我有一个包含动态内容的div-因此它没有固定的高度:

.dynamic-height {
   color: #000;
   font-size: 12px;
   height: auto;
   text-align: left;
}
<div class='dynamic-height'>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
</div>

我想仅使用CSS将margin-top.dynamic-height设置为等于(the height of the div - 10px)的值。

如果得到高度,我可以使用CSS calc()函数。

我该怎么做?

css css3
2个回答
27
投票

不幸的是,由于CSS不是一种返回除浏览器调整其样式的规则以外的任何类型的数据的语言,因此无法通过CSS“获取”元素的高度。

您的分辨率可以使用jQuery来实现,或者,您也可以使用CSS3的transform:translateY();进行伪造>


CSS路线

如果我们假设您的目标div在这种情况下为200像素高-这意味着您希望div的边距为190像素?

这可以通过使用以下CSS来实现:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

在这种情况下,重要的是要记住,translateY(100%)会将有问题的元素向下移动其自身的总长度。

此路线的问题在于,它不会将其下方的元素推到有余量的地方。


jQuery路线

如果伪造它对您不起作用,那么您的下一个最佳选择就是实现一个jQuery脚本,为您添加正确的CSS。

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

11
投票

您可以使用CSS calc参数来动态计算高度,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.