如何使用 CSS 自动调整图片大小以适合 div 容器?
在网页中,如果你想自动调整图片大小以适合 div,你需要围绕高度、宽度、最大宽度和最大高度属性。要自动调整图片大小以适合 div 容器,我们在 img 标记上设置了以下 CSS 属性 -
max-width: 100%; max-height: 100%;
设置图片
首先,我们在 div mydiv 中使用 img 标记设置了一张图片 -
<div id="myDiv"> <img src="https://tutorialspoint.com/behave/images/behave.jpg"> </div>
调整容器高度和宽度
我们已经将 mydiv 的高度和宽度设置为 auto,以允许自动调整大小的 div。如果 高度:auto;元素将自动调整其高度以正确显示其内容,如下所示 -
#myDiv { height: auto; width: auto; border: 2px solid blue; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
调整容器内的图片
现在,我们已经在 divv 中设置了图片,并使用以下 CSS 属性 max-width 和 max-height 来允许自动调整大小,而不会有任何问题 -
#myDiv img { max-width: 100%; max-height: 100%; margin: auto; display: block; }
示例
现在,让我们看一个使用 CSS 自动调整图像大小以适合 div 容器的示例 -
<!DOCTYPE html> <html> <head> <style> #myDiv { height: auto; width: auto; border: 2px solid blue; } #myDiv img { max-width: 100%; max-height: 100%; margin: auto; display: block; } </style> </head> <body> <div id="myDiv"> <img src="https://tutorialspoint.com/behave/images/behave.jpg"> </div> </body> </html>
广告