[英]CSS resize div whilst maintaining aspect ratio of containing image
我有一個里面有 img 的 div 容器:
<div id='triangle'>
<img src='/static/triangle.png' style='position: absolute; height: 100%; width: 100%'>
</div>
如何將 div 的大小調整為 500px 的高度並保持縱橫比? 我試過了:
#triangle
{
position: absolute;
height: 500px;
width: auto;
}
但它不起作用:或者:
#triangle
{
position: absolute;
max-height: 500px;
max-width: 500px;
}
創建一個 500x0 像素的 div。
您應該從圖像標簽中刪除“位置:絕對”。 因為 parent 已經用 position: absolute 設置了樣式;
嘗試應用此樣式並從元素中刪除內聯樣式:
#triangle {
height:500px;
width: max-content;
}
img {
height:100%;
}
您需要做的是根據您的需要使 img 標簽的寬度或高度屬性之一等於 100%,另一個等於 auto。
此外,您的 img 標簽不得具有position:absolute
功能。 因此,您的代碼應如下所示:
<!DOCTYPE html>
<html>
<head>
<style>
#triangle
{
position: absolute;
height: 500px;
width: 500px;
}
</style>
</head>
<body>
<h2>HTML Image</h2>
<div id="triangle">
<img src='/static/triangle.png' width="100%" height="auto">
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.