Pictures play an important role in web design. Appropriately setting the width and height of pictures can make the web page more beautiful and have a more reasonable structure. So, how to set the width and height of the image through CSS?
First of all, you need to pay attention to the following points when inserting pictures into HTML code:
Therefore, it is a better choice to use the CSS background-image property and background-size property to set the width and height of the image. The following are some practical CSS tips:
① Set fixed width and height
Use the width and height attributes in CSS to set the fixed width and height of the image, as shown below:
.img{ width: 300px; /*设置图片宽*/ height: 200px; /*设置图片高*/ }
Of course, it can also be set by abbreviation:
.img{ width: 300px; height: 200px; /*用“;”隔开即可*/ }
② Adaptive width and height according to the container
Sometimes, we need to realize that the image adapts to the width as the size of the container changes. high. At this time, you can use the background-size attribute in CSS and set its value to "contain" or "cover".
"contain" means that the image is fully displayed, but it may not be wide or tall enough;
"cover" means that the image fills the container, but we cannot guarantee that the image is fully displayed.
As shown below:
.img{ background-image: url(./img/bg.jpg); /*设置背景图片地址*/ background-size: contain; /*或者:background-size: cover;*/ }
③ Scale the image proportionally
In order to ensure that the proportion of the image remains unchanged, we can set a "padding-top" attribute with a value of percentage . It will determine the height of the image based on the width of the parent container, thereby achieving proportional scaling.
.img{ background-image: url(./img/bg.jpg); /*设置背景图片地址*/ padding-top: 50%; /*比例数值等于图片的高/宽*100% */ background-size: cover; /*铺满背景容器*/ }
The above are three common ways to set the width and height of CSS images. Through flexible use, we can easily optimize image display in web design and improve user experience.
The above is the detailed content of How to set the width and height of the image in css. For more information, please follow other related articles on the PHP Chinese website!