'Unable to make an image non-right-clickable with absolute element in flex div
I have a problem with disabling "right click/save image as" for images.
It works as expected when I remove flex style.
In the current example it is very confusing, not just the second square is not "protected" for right click at all but the first one is only partly protected, the transparent rectangle is "clickable" at the right side.
I would love to fix this code instead of using another solution.
Code:
.post-thumbnail {
position: relative;
overflow: hidden;
max-width: 768px;
}
.post-thumbnail:before {
display: block;
position: absolute;
top: 0;
left: 0;
content: "\020";
width: 50%;
height: 50%;
background: #232649;
opacity: 0.8;
z-index: 5;
}
.post-thumbnail img {
width: 100%;
height: auto;
z-index: 1;
}
<ul>
<li>
<div style="display: flex; justify-content: center;">
<div class="post-thumbnail">
<img src="https://www.w3schools.com/css/img_forest.jpg" width="300" height="200">
</div>
<div class="post-thumbnail">
<img src="https://www.w3schools.com/css/img_forest.jpg" width="300" height="200">
</div>
</div>
</li>
</ul>
Solution 1:[1]
You'll need javascript for this, something like the example below.
// Remove right-click for images.
const images = document.querySelectorAll('img');
images.forEach((img) => img.addEventListener('contextmenu', event => event.preventDefault()));
.post-thumbnail {
position: relative;
overflow: hidden;
max-width: 768px;
}
.post-thumbnail:before {
display: block;
position: absolute;
top: 0;
left: 0;
content: "\020";
width: 50%;
height: 50%;
background: #232649;
opacity: 0.8;
z-index: 5;
}
.post-thumbnail img {
width: 100%;
height: auto;
z-index: 1;
}
<ul>
<li>
<div style="display: flex; justify-content: center;">
<div class="post-thumbnail">
<img src="https://www.w3schools.com/css/img_forest.jpg" width="300" height="200">
</div>
<div class="post-thumbnail">
<img src="https://www.w3schools.com/css/img_forest.jpg" width="300" height="200">
</div>
</div>
</li>
</ul>
Or a purely html/CSS approach that won't actually solve your issue.
.post-thumbnail {
position: relative;
overflow: hidden;
max-width: 768px;
}
.post-thumbnail:after {
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
content: "";
opacity: 0.8;
z-index: 1;
user-select: none;
}
.post-thumbnail img {
width: 100%;
height: auto;
z-index: 1;
}
<ul>
<li>
<div style="display: flex; justify-content: center;">
<div class="post-thumbnail">
<img src="https://www.w3schools.com/css/img_forest.jpg" width="300" height="200">
</div>
<div class="post-thumbnail">
<img src="https://www.w3schools.com/css/img_forest.jpg" width="300" height="200">
</div>
</div>
</li>
</ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
