Get the App
SLTechnology News&Howtos  ›  Development  › 

How to adapt the height of div or img pictures with width in html5

Shulou Source: shulou.com Published: 2022-06-01 12:35:35 10月03日 Update

This article mainly explains how the height of div or img pictures in html5 adapts to the width. Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "how to adapt the height of div or img pictures with width in html5"!

First, you can use js to determine the width of the picture to get a specific value, and then use js to set the height of the picture (not specifically for everyone here).

A disadvantage of using js is that you can only adjust the height of the image when the page is refreshed, and you can't adapt to changes in the browser window size.

Second, this time I mainly use CSS to achieve the image height of the adaptive problem.

Here is the code required

(This method can display the text vertically at the top of the image, if you don't need it, you can choose the simpler code at the bottom):

Vertical centering of inline elements

.box{ width: 50%; margin: 50px auto;}.img-box{ width: 100%; position:relative; z-index:1;}.img-box img{ position:absolute; top:0; bottom:0; left:0; right:0; width:100%; margin:auto; z-index: -1; *zoom:1;}.img-box:before { content: ""; display: inline-block; padding-bottom: 100%; width: 0.1px; /* Must have a numerical value, otherwise the height cannot be supported */ vertical-align: middle;}

1. The main explanation here is the padding-bottom attribute. When its value is a percentage, it is calculated according to the width of the element. So when set to 100%, its height is equal to its width, forming a square. Of course, this value can be adjusted according to actual conditions.

2. The second thing to explain is that the pictures we refer to are laid out by absolute positioning, so that the pictures can adapt to the size of their parent elements.

Another neat way is to add padding-bottom directly to the parent element of img

.img-box{ padding-bottom:100%;}.img-box img{ position:absolute; top:0; bottom:0; left:0; right:0; width:100%; margin:auto;} At this point, I believe that everyone has a deeper understanding of "how div or img image height adapts to width in html5", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Pictures height width elements that is values methods time simplicity code content size reality learning adjustment practicality deeper interest practicality attributes Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft vpn Shulou Technology OPPO Reno MariaDB