I want to enlarge pictures by clicking and be able to scroll them if necessary. Enlarged pictures should be positioned relative to the screen, i.e., position: fixed
I want to do it without using JavaScript, i.e., only using CSS and HTML.
I was able to display the fixed scrolling image:
.widepicture-container {
position: fixed;
width: 200px;
height: 300px;
overflow: scroll;
}
.widepicture-container img {
width: 200%;
position: relative;
top: 50%;
left: 50%;
transform: translate(-25%, -50%);
z-index: 9999;
}
<div class="widepicture-container">
<img src="images/default.jpg" alt="Картинка"/>
</div>
But when I try to add click-to-zoom, the scrolling breaks.
<details><summary>Spoiler</summary>
<div style="background-color: #a1a1a1;">
<div class="widepicture"> <img src="images/p2.png" alt="" tabindex="0" />
<div></div></div>
</details>
.widepicture{
-moz-user-select: none; user-select: none;
overflow: scroll;
}
.widepicture img{
width: var(--wide-picture-width);
cursor: zoom-in;
display: flex;
}
.widepicture img:focus {
position: relative;
width: 200vw;
top: 25%;
z-index: 31;
overflow: scroll;
}
.widepicture img:focus ~ div {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 25;
background: rgba(200,200,200,.7);
cursor: zoom-out;
}
.widepicture:focus-within {
position: fixed;
top: 15%;
overflow: scroll;
overflow-y: scroll;
overflow-x: scroll;
}
Why does this happen and how can I make scrolling work?
The problem is you're using 'position: fixed'. This approach takes the element out of the normal document flow, and it becomes fixed relative to the viewport.
If you wanna achieve this feature without writing any js code. You can use a combination of 'position: absolute' and 'position: relative' like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
}
.widepicture-container {
position: relative;
width: 100vw;
height: 100vh;
overflow: hidden;
}
.widepicture-container img {
width: 100%;
height: auto;
cursor: zoom-in;
}
.widepicture-container img:focus {
position: absolute;
top: 0;
left: 0;
width: 200vw;
height: 200vh;
object-fit: contain;
z-index: 2;
cursor: zoom-out;
}
.widepicture-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(200, 200, 200, 0.7);
z-index: 1;
cursor: zoom-out;
display: none;
}
.widepicture-container img:focus ~ .widepicture-overlay {
display: block;
}
</style>
</head>
<body>
<div class="widepicture-container">
<img src="images/default.jpg" alt="Картинка" tabindex="0" />
<div class="widepicture-overlay"></div>
</div>
</body>
</html>