Vertical and horizontal centering with increased size (in div) using only CSS and HTML

So, for centuries I tried to achieve this. Basically, my site allows the administrator to upload a thumbnail and a thumbnail image for each item in the directory. The thumbnail is displayed on the page that the client sees, and the magnification is displayed when you hover over it.

I cannot control the size of the uploaded images (I suppose I could limit the width and height, but in this situation it would be impractical).

I would like to vertically and horizontally center this zoom. It is contained in a div with position: fixed; . I believe (although I don’t have the code in front of me at the moment) that I am currently using something like the following:

 .image-enlargement { position: fixed; left: 50%; top: 50%; width: 300px; height: 400px; margin-left: -150px; margin-top: -200px; } 

Perhaps I changed it to use jQuery - I don’t remember, although it was so long ago when I last worked on this fragment of the website. Now, what I would like to do with the code above is to subtract the specifications for width, height, and margin so that the image, no matter how large or small, should be accurately centered and without using JavaScript.

Has anyone ever done this before? If so, how? I am sure there must be some way to achieve this result, but it did not come up with a pure CSS / HTML solution.

Edit: JSFiddle at http://jsfiddle.net/Y7xAp/ .

+4
source share
3 answers

Not sure how useful this would be in your situation, but the way is to display the image as a background image. The code might look something like this:

 #container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: transparent url('myImage.jpg') center center no-repeat; } 

Then the browser will correctly calculate the position of the image vertically and horizontally. Then put the event on onClick or something like that to detect when they want the image to disappear.

+2
source

If you could post your allowance here, it would be great so that we can help you better. As for the size of the image element, you can specify its width and height so that any size of the image that the user has uploaded will still be the same. You can do this as follows: <img src="<image url>" height="100" width="100"/>

0
source

The best way to center divs horizontally and vertically with CSS is through the flex-box.

Use display: flex on the container and margin: auto on the inner element.

Remember: this is a good solution for new browsers, and the container must have a height for display: flex works correctly. In this case, I use the vh / vw module (1/100 of the window height / width).

Try using this:

 .image-enlargement { position: relative; display: flex; width: 100vw; height: 100vh; } .image-enlargement img { margin: auto; } 

Read more about flex-box and vw / vh modules:

0
source

Source: https://habr.com/ru/post/1337245/


All Articles