Creating a selection area with CSS that appears transparent is a straightforward process

I'm currently exploring ways to implement a UI effect on a webpage that involves highlighting a specific area while covering the rest of the page with a semi-transparent black overlay, all using CSS only. What is the most common approach to achieving this desired effect? My goal is to have the highlighted area fully clear and interactive, and the surrounding areas dimmed.

It's worth mentioning that I am seeking a solution that steers clear of JavaScript and intricate HTML structures if feasible, but also should be compatible with the newest browser versions.

Imagining something akin to this:

https://i.sstatic.net/lDnUG.png

Can CSS alone accomplish something like this, for instance:

/* An overlay spanning the entire viewport */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7); /* Semi-transparent black */
}

I initially experimented with mask CSS properties for defining the selection area, although unsure if it's considered the optimal method.

Please note: The rectangle should be interactive (movable, resizable).

Update: A potential solution might involve utilizing box-shadow for the dimming effect outside the selected area.

.my-rectangle {
  position: absolute;
  z-index: 10001;
  border: 2px solid rgba(255, 255, 255, 0.6);
  background-color: rgba(102, 179, 255, 0.2);
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5); /* Dimmed background outside the rectangle */
}

Answer №1

You can achieve the effect of a semi-transparent border or box-shadow by using an element or pseudo-element with a transparent background-color. Here's an example:

body {
  margin: 0;
}

body::after {
  content: "";
  display: block;
  background-color: transparent;
  position: fixed;
  inset: 0;
  border: 20vh solid rgba(0, 0, 0, 0.7);
}
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Answer №2

It seems like you're looking to create an interactive section specifically within the "hole". One way to achieve this is by adding pointer-events: none; to the block and utilizing elements inside that will have pointer-events: auto;. For example:

body {
  overflow:hidden;
}

.frame {
  --width: 200px;
  --height: 150px;
  position: fixed;
  width: var(--width);
  height: var(--height);
  z-index: 666;
  box-shadow: 0 0 0 100vmax rgba(0,0,0,.5);
  left: calc(50% - var(--width) / 2);
  top: calc(50% - var(--height) / 2);
  pointer-events: none;
}

.frame i {
  position: absolute;
  pointer-events: auto;
}

.frame i:nth-child(1) {
  inset:-100vmax -100vmax -100vmax 100%;
}

.frame i:nth-child(2) {
  inset:100% -100vmax -100vmax;
}

.frame i:nth-child(3) {
  inset:-100vmax 100% -100vmax -100vmax;
}

.frame i:nth-child(4) {
  inset:-100vmax -100vmax 100%;
}
<div class="frame">
  <i></i>
  <i></i>
  <i></i>
  <i></i>
</div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit, delectus accusantium laborum maxime laudantium quos aspernatur ratione ea dignissimos odio dicta omnis voluptatibus quo sit adipisci. Ad, corporis, ex, accusantium ullam nostrum eum nisi quidem obcaecati libero veniam error consequuntur magni magnam molestiae praesentium iste expedita odio reprehenderit labore a dolorum aperiam quasi perferendis ea reiciendis temporibus sint natus atque dolores perspiciatis doloremque corrupti harum enim cumque eveniet dolor quaerat maxime. Libero, a, similique, tempora dolore optio vero amet iusto blanditiis minima autem aspernatur vel alias nesciunt quo ut aliquam natus veniam tenetur dignissimos at mollitia praesentium reiciendis enim laboriosam quae. Saepe, voluptates, omnis dolores quam aut accusantium doloremque? Earum, odio, odit dolorum optio amet ipsam voluptates quaerat non enim iusto ipsa deleniti eaque tenetur dignissimos commodi similique aliquid quo hic unde exercitationem obcaecati molestiae culpa accusamus nemo harum sed atque veritatis consectetur numquam voluptate! Minus, nam voluptatem consequuntur numquam enim mollitia earum tenetur veritatis dolor quas. Alias, provident in sunt ipsum minus asperiores sit. Rerum, ullam unde qu...

Answer №3

.container {
    z-index: 10;
    width: 300px;
    height: 150px;
    background: transparent;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    border: 5px solid rgba(100, 45, 65, 0.5);
}
<div class="container"></div>

Here is the final output:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with Sequelize Errors

After reviewing the code provided, I am curious if it would be sufficient to simply chain one .catch() onto the outermost sequelize task rather than attaching it to each individual task, which can create a cluttered appearance. Additionally, I am wonderin ...

Is there a way to see the countdown timers in Angular 7?

Is there a way for me to view my timer's countdown as it starts? I have attempted to bind it to a variable, but all I see is [object Object]: setTime(time) { if (this.settime >= 5 ) { this.currentTime = time; this.alerttime = thi ...

When the CSS animation has finished in JavaScript

I am currently developing a game using HTML/JavaScript, and I have implemented a "special ability" that can only be activated once every x seconds. To indicate when this ability is available for use, I have created a graphical user interface element. Since ...

Clicking on the images will display full page versions

Apologies for not making an attempt just yet, but I'm struggling to locate what I need. Here's the menu structure in question: <div class="overlay-navigation"> <nav role="navigation"> <ul class="test"> & ...

Tips for accessing various JSON objects from a JSON document

My task involves extracting specific information from a JSON file using AJAX and jQuery. The structure of my JSON data is as follows: "Footwear": { "Adidas": [ { "id" : 0, &q ...

Is it possible to identify a legitimate JSONP response?

My goal is to exchange data with a web service on a separate server that lacks CORS support. I am required to utilize JSONP for this purpose. The service mandates authentication, and when the user is in an SSO environment, they are seamlessly passed throug ...

Guide to placing a basic div directly over a basic html table td

I need to create a simple html table with labels in one column and content in another. What I want to achieve is placing a div over the content td while keeping the label visible. I am looking for the most efficient way to do this, possibly making the seco ...

The AJAX response containing jQuery is failing to produce any visible changes

On Page 1 of my website, there is a form that, upon submission, loads Page 2 using jQuery. This process involves calling a PHP page and displaying the output on Page 1 without actually reloading the entire page. To maintain security, I have set up session ...

Send the Vue component as an argument to the function

Currently, I am in the process of transferring a project to Vue and utilizing Muuri as a layout manager. In my code, I have the following snippet: grid.add(itemElem, { layout: false, active: false }); The variable itemElem used to be an HTML element c ...

Incorporating Vue.js components into PHP applications

I am currently working on a project using PHP in conjunction with Vue.js and vue-router. In my PHP form handler, I have implemented functionality to send emails. What I am trying to achieve is redirecting the user to a specific component within my Vue ap ...

Ways to customize easypiechart appearance with CSS styling

I am looking to create a circular counter similar to the one shown below. I have tried using easy-pie-chart but I am unsure how to style the circles to look like the example provided. Is there a way to achieve this through CSS? Any recommended resources o ...

Accessing the phone number input from a form in Rails and verifying its presence in the database. Implementing distinct ajax responses based on the existence of the value

Looking for a way to verify phone numbers? The process involves users entering a phone number, submitting the form, and cross-referencing it with a database of phone number records to determine if it's valid. My goal is to provide different AJAX respo ...

Applying various Angular filters to an array of objects within HTML select elements

I'm fairly new to working with JS and the rather challenging learning curve of AngularJS. I have an array containing numerous objects with the relevant properties listed below: $scope.myRecs = [{country: 'Ireland', city: 'Dublin&apos ...

When using a wildcard router in Node.js/Express.js, the static router may not be recognized

While using this specific route along with my other routes, I encounter an issue with serving static files: var public_dir = path.join(__dirname, 'public'); app.use('/public', express.static(public_dir)); However, when I add the follo ...

The entire DOM in Angular2+ flickers upon loading a component using ngFor

I am facing an issue where, after a user clicks on an item to add it to a list and then renders the list using ngFor, there is a flickering effect on the screen/DOM. The strange thing is that this flicker only happens after adding the first item; subsequen ...

The looping function in JavaScript iterates 20 times successfully before unexpectedly producing NaN

run = 0 function retrieveItemPrice(id){ $.get('/items/' + id + '/privatesaleslist', function(data){ var htmlData = $(data); var lowestPrice = parseInt($('.currency-robux', htmlData).eq(0).text().replace(',& ...

When pressed, the button changes color to a vibrant shade of blue, and not just a simple outline

I'm experiencing an issue with a button that turns blue when the user holds onto it for a while on mobile. You can see an example in the image below: Adding ::selected or outline did not resolve the problem as the entire button still turns blue for a ...

When sending a form with a POST request in NODE, the data can be missing

I'm having trouble with setting up routes in an API and getting data from simple forms. Take a look at this basic HTML form: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>test form</titl ...

Error: The variable $ has not been declared in the context of the function iterateId

I understand that there are many questions on SO related to this error, but my issue is a bit unique. In my code, I am using a forEach loop to retrieve the IDs and text of elements as shown below: function iterateId(id){ $("input[id*='" + id + ...

Include web browsing history

In my ASP.Net/VB project, I am facing an issue with floating DIVs. Whenever users try to close the floating DIV by clicking on the back button in their browser, it creates a confusing experience. My solution is to add a "#" entry to the browser history wh ...