[英]maintain aspect ratio of a child div with both height and width changes of the parent
[英]Maintain aspect ratio of div in %, knowing the height and width in px
我要向div添加背景圖片。
<div class="image" style="background-image: url(...)>
</div>
CSS是動態的。 例如...
.image {
width: 65%;
height: ? (trying to figure out the value)
}
我正在嘗試在js中計算高度,以保持圖像的長寬比。
如果我知道原始圖像的寬度和高度(以px為單位),如何基於CSS的寬度(以%設置)在CSS中設置正確的高度值,以保持圖像尺寸比率?
問題看起來像這樣:
圖片寬度= 300像素
圖像高度= 520px
CSS中的寬度= 65%
CSS中保持縱橫比的高度=?
我無法使用父容器的寬度進行計算。
我無法使用offsetWidth
獲取以px為單位的動態圖像寬度。
我不能只在div中使用圖像。
您無需知道圖像的原始尺寸。 為圖像設置一個尺寸會自動設置另一個尺寸,以保持寬高比。 這是一個例子:
原始圖片(400像素x 300像素)
<img src="https://i.stack.imgur.com/lKtag.png"/>
調整大小的圖像(占容器寬度的40%)
<img src="https://i.stack.imgur.com/lKtag.png" style="width:40%"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.