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:

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

Is there a way to halt the polling process for the specific API handling the background task?

I have been using this polling function for executing background tasks. export const poll = ({ fn = () => {}, validate = (result) => !!result, interval = 1000, maxAttempts = 15, }) => { let attempts = 1; // eslint-disable-next-line con ...

How can I generate a fresh window/frame within my Javascript canvas?

Is there a way to open a new frame or window within the canvas using JavaScript? I am working on a game project where I want to implement a feature that displays additional information on a menu screen when a button is pressed. Currently, I have managed to ...

Display a compilation either in the backend or the frontend

I'm fairly new to NodeJS and I could really use some advice. I currently have a webpage that displays a list of users, which is retrieved from a collection using Mongoose. I am aware of two different ways to display this list: 1) One option is to que ...

Working with extensive amounts of HTML in JavaScript

Is there a way to dynamically load large amounts of HTML content in JavaScript? I'm struggling to figure out how to insert all the HTML content into the designated space within the JavaScript code. If anyone knows a different approach or solution, ple ...

Enclose Words Inside Unconventional Outline

Place text within a uniquely shaped border… I am attempting to achieve this goal in the most responsive and backward compatible way possible. I understand that compromise may be necessary. I have made progress with the help of this thread, but the svg ...

An unexpected page transition occurs when attempting to delete a link

I've successfully created an HTML table that dynamically adds rows and provides an option to delete the current row. Each row represents data retrieved from MongoDB, and upon clicking the delete button, I aim to delete the corresponding item from the ...

What could be causing my website to extend beyond 100% width?

I've been working tirelessly on solving this issue for the past week, but unfortunately, I haven't had any luck finding a solution. The problem arose as I was designing a launch page for a program that my friend is developing. Despite setting the ...

When the parent div overflows, the child div remains hidden within the boundaries of the parent div

<section class="margin-top-30"> <div class="row" style="position: relative;"> <div class="col-sm-4"> <div class="lightbgblock" style="overflow-x:visible;overflow-y:scroll;"> ...

The link in the navigation bar is not functioning correctly

Let me break down the issue I'm facing here. The problem arises with the navigation buttons that have sub-lists nested within them (ul>li>ul). When attempting to click on these buttons, the link does not work unless I specifically click on the text it ...

Enhance Your Search Bar with Ajax and JQuery for Dynamic Content Updates

My goal is to create a search bar that dynamically loads content, but I want the actual loading of content to start only after the user has finished typing. I attempted a version of this, but it doesn't work because it doesn't take into account ...

Clicking the button in Angular should trigger a series of functions to be

It seems like I'm struggling with a simple question due to my lack of experience in this area. Any guidance or help would be greatly appreciated. I have a button that should trigger multiple functions when clicked, all defined in the same ts file. Wh ...

Display an aspx page within a div container

I am using the following code to load an aspx page in a div tag. Unfortunately, it's not working as expected. Can someone please assist me in resolving this issue? <script type="text/javascript"> $(document).ready(function () { $(&a ...

Retrieve the variance between two arrays and store the additions in AddedList and the removals in RemovedList using typescript

I am still getting the hang of Typescript and I am trying to figure out the best solution for my issue. I have two arrays, A and B, and I need to identify the difference between them in relation to array A. The goal is to separate the elements that were ad ...

What is the correct way to execute a jQuery trigger on a checkbox or radio button to simulate a user clicking on it?

My current page utilizes can.js, making it challenging to replicate the issue on jsfiddle.net. The result I am experiencing is as follows: When I click on a checkbox (or even a radio button), an input text box should update accordingly (for example, displ ...

Retrieving custom attribute values during a drop event in Jquery drag and drop operations

I'm currently working on a moodboard creator, but I've hit a snag while trying to transfer the values from custom attributes of an image to a new div once the drop action is completed. Every time the drop is finished, it always fetches the value ...

Can someone explain to me how I can customize the background of a bootstrap container?

Currently, I am working on an EJS login project and I have created a style.css file with the following code: [theme="bloodRed"] { background-color: #ff2424; color: #e571e1; accent-color: #00ff00; } In my register.ejs ...

Disabling the ability to edit the rightmost portion of an input number field

I am looking for something similar to this: https://i.stack.imgur.com/ZMoNf.jpg In this case, the % sign will be shown in the input field by default and cannot be changed or removed. The user is only able to modify the number to the left of the % sign. P ...

Axios removes the async functionality

Is there a way to achieve the same functionality without using the async function? async EnvioLogin() { const response = await axios.post("api/auth/login", { email: this.email, password: this.password, }); localStorage.setItem(" ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

Retrieve information from the existing URL and utilize it as a parameter in an ajax request

Currently, I am working on a website with only one HTML page. The main functionality involves fetching the URL to extract an ID and then sending it to an API using an AJAX call. Upon success, the data related to the extracted ID is displayed on the page. H ...