简体   繁体   中英

Overlay a semi-transparent box over any HTML element

I have an HTML file which I cannot control the content of . All I can do is inject a CSS file and/or JavaScript file (including libraries such as jQuery if required).

In the HTML there will be elements which need to be highlighted and have a tooltip added (let's say for example they have a specific data- attribute) but they are not conveniently located in specific containers to which I can apply a style. These elements could be <span> , <a> , <img> , <div> or just about anything else (inline or block).

I'd like to solve this with pure CSS if I can, but I'm willing to use JavaScript to modify the DOM if needs be, however the final HTML must have the same layout as the original, which just the highlights floating over the specific elements.

For example, I might have some HTML like this:

<body>
    <p>This is a sample line of text with <a href="#">a link</a> in the middle that should be highlighted</p>

    <p>This is a sample line of text with <a href="#" data-highlight="true">a link</a> in the middle that should be highlighted</p>
</body>

Which should end up looking like this:

在此处输入图片说明

I would go for something like this. As you wished, CSS-only, no changes in HTML.

  • *[data-highlight="true"] - selects all elements with data-highlight="true"

  • background: rgba(255, 0, 0, 0.5) - gives rgba background with 50% opacity.

Thing to remember

If there are some elements with specific CSS rules for position below code needs to be adjusted. For example if one <span> needs to have below rules but already has position: absolute position value can not be changed to relative and specific rule must overwrite below.

Snippet

 *[data-highlight="true"] { position: relative; } *[data-highlight="true"]:after { display: block; content: ''; position: absolute; top: 0; left: 0; height: 100%; width: 100%; background: rgba(255, 0, 0, 0.5); border: 1px solid red; } 
 <body> <p>This is a sample line of text with <a href="#">a link</a> in the middle that should be highlighted</p> <p>This is a sample line of text with <a href="#" data-highlight="true">a link</a> in the middle that should be highlighted</p> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM