I want to know how to automatically specify the height in the div with the background-image specified.

Asked 1 years ago, Updated 1 years ago, 325 views

What do you want to do

  • I would like to know how to automatically indicate height in a div with background-image, max-width specified.
    • If it exceeds max-width, I want to reduce it to max-width.
  • If possible, I'd like to do it only with css.
  • If it exceeds max-width, I want to reduce it to max-width.

Prerequisites

  • The image size is indefinite and can be small or large.
  • The div max-width specifies 400px.

Reference Code

  • In this example, an image with a width of 800px is reduced to 400px with max-width, so you want to set a value equivalent to height:1000px.
<html lang="ja">
<body>
<div style="background-image:url(./test.png);background-repeat:no-repeat;background-size:cover;max-width:400px;">/div>
</body>
</html>

Verification Image_800x2000px

html css

2023-01-16 22:50

1 Answers

If the aspect ratio of the image is constant, you can simply specify the aspect-ratio property.

If the aspect ratio is not constant, I don't think CSS alone can do it.Load the image in Image() and update the height properties of the naturalWidth element calculated from naturalHeight.


2023-01-17 05:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.