簡體   English   中英

如何計算 div 的最頂部和底部之間的高度:0

[英]How to calculate height between the very top of a div and bottom: 0

我希望能夠將一個div放在另一個div的頂部。 對於圖像中的示例,我有兩個div 第一個位置是right: 10px; bottom: 10px; . 我希望能夠以同樣的方式 position 第二個div ,但是bottom比第一個div的最頂部高10px 要動態地做到這一點,我需要在第一個div的最頂部和bottom: 0

我怎樣才能用 JavaScript 或 JQuery 得到它?

在此處輸入圖像描述

<div class="div1">This is the first div</div>
<div class="div2">This is the second div</div>
.div1 {
    position: absolute;
    bottom: 10px;
    right: 10px;
    display: inline-block;
    padding: 10px;
    background-color: #990;
}
.div2 {
    display: inline-block;
    padding: 10px;
    background-color: #099;
    //position: absolute;
    //right: 10px;
    //bottom: ...;
}

您可以使用display: flexflex-direction: column-reverse 對於 10px 的間隙,您可以對所有 div 使用margin-bottom:10px

請參閱下面的片段:

 .main{ position: absolute; right: 10px; bottom: 10px; display: inline-block; display: flex; align-items: flex-end; flex-direction: column-reverse; }.div{ padding: 10px; margin-bottom: 10px; }.div:first-child{ margin-bottom: 0; }.div1 { background-color: #990; }.div2 { background-color: #099; }.div3 { background-color: #909; }
 <div class="main"> <div class="div div1">This is the first div</div> <div class="div div2">This is the second div</div> <div class="div div3">This is the third div</div> </div>

你也可以在這里測試

在 js 中,訪問第一個 div offsetHeight 並向其添加 10px。 你得到第二個div的高度。

el.offsetHeight + 10;

在 jQuery 中,$(el).getBoundingClientRect() 給出了元素的高度。

在 JavaScript 中,您可以使用 clientHeight 來獲取div1的高度,添加您想要的任何數字並將其設置為您可以用來設置 div2 bottom position 樣式的變量。

建議在 CSS 中添加box-sizing: border-box以幫助避免任何隨機定位/調整大小錯誤。

 const div1 = document.querySelector(".div1"); const div2 = document.querySelector(".div2"); // Here we are creating the new 'position' variable // let position = div1.clientHeight + 20; // Here we are styling div2's bottom position with the above variable.// // You can use whatever unit you want from here.// div2.style.bottom = position + "px";
 * { box-sizing: border-box; }.div1 { display: inline-block; position: absolute; padding: 10px; bottom: 10px; right: 10px; background-color: #990; }.div2 { display: inline-block; position: absolute; padding: 10px; right: 10px; background-color: #099; }
 <div class="div1"> <p>Div 1</p> </div> <div class="div2"> <p>Div 2</p> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM