D
D
Dubrovin2020-04-29 11:39:26
JavaScript
Dubrovin, 2020-04-29 11:39:26

Is it possible to get the height/width of background with background-size: cover?

Hello,
the DIV block has its background image set to background-image: url() and image size set to background-size: cover.
Is it possible via JS to get the height/width of the rendered background image in pixels?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
londhor, 2020-04-29
@Dubrovin

Difficult, but possible:
1. Get the initial value of the picture itself in px (conditionally 1920x1080 px)
2. Get the size of the div in which the picture is (let's say 1440x900px).
In our case, the BG size will be calculated from the height of the image and the height of the block.
Accordingly, 1080/900 = 1.2. where 1.2 is the ratio by which your image is scaled down.
Now, knowing the ratio, we find out the width. To do this, divide the width of the image by the ratio (1920/1.2) and get 1600 px.
Result: background size 1600x900px.
Cases where the picture or block is vertical I think you can modify it yourself, by analogy with the example above. The main thing is to determine what the size of the image in the block is based on. I think in my example you can easily add the necessary functionality

L
Lord_Dantes, 2020-04-29
@Lord_Dantes

Is it possible to get the height/width of a background with background-size: cover?

Actually yes. But it will be the width and height equal to the content or the pre-set width and height rules.
In fact, it is not possible because the picture itself will not stretch to the size it needs, because this is a background.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question