為了對應(yīng)用程序進(jìn)行響應(yīng)式設(shè)計,我們還需要使圖像響應(yīng)式。如果圖像沒有響應(yīng),應(yīng)用程序中就會發(fā)生溢出,并且看起來最糟糕。
因此,我們還需要根據(jù)父元素的尺寸按比例增加或減少圖像的尺寸。在這里,我們將學(xué)習(xí)使用 CSS 按比例調(diào)整圖像大小的各種方法。
語法
用戶可以按照以下語法使用“width”CSS 屬性按比例調(diào)整圖像大小。
img { width: 100%; height: auto; }
登錄后復(fù)制
在上面的語法中,我們?yōu)閳D像設(shè)置了 100% 寬度和自動高度,使其具有響應(yīng)能力。
示例
在下面的示例中,我們創(chuàng)建了 div 元素,并指定了“image”類名稱,并在 div 元素內(nèi)添加了一個圖像作為子元素。
在 CSS 中,我們以百分比形式設(shè)置 div 元素的寬度,等于總寬度的 30%。此外,我們還為圖像設(shè)置了 100% 寬度和自動高度。用戶可以更改屏幕尺寸并觀察圖像尺寸與屏幕尺寸成比例地減小和增大。
<html> <head> <style> .image { width: 30%; margin: 0 auto; border: 3px solid red; padding: 10px; } img { width: 100%; height: auto; } </style> </head> <body> <h2> Using the <i> width CSS property </i> to resize image proportionally </h2> <div class = "image"> <img src = "https://www.tutorialspoint.com/python_pillow/images/tutorials_point.jpg" alt = "logo"> </div> </body> </html>
登錄后復(fù)制
示例
在下面的示例中,我們使用了“object-fit: contains”CSS 屬性來按比例縮小圖像的大小。在這里,我們設(shè)置了圖像的父 div 元素的比例寬度。此外,我們還為“img”元素使用了“object-fit: contains”CSS 屬性。在輸出中,用戶可以觀察到圖像是響應(yīng)式的,并且其尺寸根據(jù) div 元素的尺寸而變化。
<html> <head> <style> .image { width: 30%; margin: 0 auto; border: 3px solid red; padding: 10px; } img { width: 100%; height: 50%; object-fit: contain; } </style> </head> <body> <h3> Using the <i> object-fit: contain CSS property </i> to resize image proportionally </h3> <div class = "image"> <img src = "https://www.tutorialspoint.com/python_pillow/images/tutorials_point.jpg" alt = "logo"> </div> </body> </html>
登錄后復(fù)制
示例
在下面的示例中,我們使用“background-size”CSS 屬性按比例更改圖像的尺寸。在這里,我們?yōu)?div 元素設(shè)置了背景圖像。此外,我們還使用“contain”作為“background-size”CSS 屬性的值。它將圖像分散到整個 div 中。如果 div 元素的尺寸增加,圖像大小也會增加。如果 div 元素的尺寸減小,圖像的尺寸也會減小。
<html> <head> <style> .image { width: 30%; min-height: 30%; margin: 0 auto; border: 3px solid red; padding: 10px; background-image: url("https://www.tutorialspoint.com/python_pillow/images/tutorials_point.jpg"); background-size: contain; background-repeat: no-repeat; } </style> </head> <body> <h3> Using the <i> background-size CSS property </i> to resize image proportionally </h3> <div class = "image"></div> </body> </html>
登錄后復(fù)制
用戶學(xué)會了按比例更改圖像尺寸。在這里,我們需要做的就是以百分比而不是像素或 rem 來設(shè)置圖像尺寸。此外,用戶還可以使用“background-size”CSS 屬性按比例更改背景圖像的尺寸。
以上就是使用 CSS 按比例調(diào)整圖像大小的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!