I have applied transform: rotate(90deg);
CSS on my image, but it is also rotating ALT text, which is causing this text to appear over other image whenever image is not found.
Is there any why in which I can prevent ALT text from getting rotated?
<div>
<img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL">
</div>
div { margin-top:50px; }
<div>
<img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL">
</div>
EDIT
I am having a lot of images on the page.
You can use the onerror
handler to remove the styles from your image:
function onImageNotFound() {
document.getElementById('imgTest').style.transform = 'none';
}
div { margin-top:50px; }
<div>
<img id="imgTest" style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL" onerror="onImageNotFound();">
</div>
And here is an inline version:
div { margin-top:50px; }
<div>
<img style="transform: rotate(90deg);" alt="User Name" src="http://ImageURL" onerror="this.style.transform = 'none';">
</div>
The best solution is probably to apply the transformation only on loaded images:
for (let img of document.querySelectorAll("img")) {
img.addEventListener("load", function(){
this.classList.add("rotated");
});
}
div { margin-top:50px; }
.rotated { transform: rotate(90deg); }
<div>
<img alt="User Name" src="http://ImageURL">
</div>
<div>
<img alt="User Name" src="https://dystroy.org/spacebullet-48.png">
</div>
If you are only applying the effect to one (small) image you could do something like this with CSS.
Place a non-rotated copy of the image behind the rotated image. If the image loads, the rotated version will show. If it fails, the alt text of the non-rotated version will show.
div {
margin-bottom: 50px;
border: 1px solid red;
position: relative;
/* hide the broken image icon */
overflow: hidden;
}
img {
display: inline-block;
vertical-align: bottom;
}
.img-rotate {
transform: rotate(90deg);
/* hide the alt text */
color: transparent;
}
.img-copy {
position: absolute;
left: 0;
z-index: -1;
}
<p>Broken image link</p>
<div>
<img class="img-rotate" alt="User Name" src="http://ImageURL">
<img class="img-copy" alt="User Name" src="http://ImageURL">
</div>
<p>Working image link</p>
<div>
<img class="img-rotate" alt="User Name" src="https://unsplash.it/200">
<img class="img-copy" alt="User Name" src="https://unsplash.it/200">
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With