An anchor(<a href=“”>) wrapping a iframe (<iframe>) does not work
The issue:
In a situation where we had an anchor wrapping an iframe but the anchor was not working properly. The iframe was showing nicely. The anchor did wrap the iframe but when we clicked on it nothing happened. The anchor did not redirect to the proper location.
The reason:
See the code segment below:
<a href="https://facebook.com"> <iframe src="https://upokary.com" width="100%"> <p>Your browser does not support iframes.</p> </iframe> </a>
It did not work because it is not a valid HTML. The element iframe must not appear as a descendant of the anchor (<a>) element. https://w3.org/TR/html-markup/iframe.html
The solution:
We can solve this issue by z-index property. Instead of wrapping the iframe with anchor, we should put the anchor and iframe as siblings. Both the siblings should have position absolute and the same width and height.
At the end the anchor should have a higher z-index value than the iframe. Please check the code segment below:
<a href="https://google.com" class="element theanchor"></a> <iframe class="element theiframe" src="https://upokary.com"> <p>Your browser does not support iframes.</p> </iframe> // CSS .element{position:absolute;width:500px;height:300px;} .theanchor{z-index:2} .theiframe{z-index:1;}