Is there a way to change the border property of an element when clicked, without causing the displacement of other elements?

I'm in the process of creating a webpage where users can choose the color and storage capacity of an item. Only one color/capacity can be selected at a time, and once chosen, it should be highlighted with a border.

The issue I encountered is that when applying the border, it displaces other elements on the page, as shown below:

https://i.stack.imgur.com/tsJqY.png

My initial thought was to give all elements a border: 2px solid rgba(0,0,0,0) to prevent displacement and then use JavaScript to modify the border properties upon selection. However, I believe this approach may not be the most elegant solution.

Below is the HTML code...

<ul>
    <li onclick="changeName('Gold')"><div class="select-color" id="gold"></div></li>
    <li onclick="changeName('Silver')"><div class="select-color" id="silver"></div></li>
    <li onclick="changeName('Space Grey'); "><div class="select-color" id="space-grey"></div></li>
</ul>

and the CSS code...

ul li {
          width: 47px;
          height: 47px;
          border-radius: 12px;
          border: 2px solid rgba(0,0,0,0);
          padding: 3px;
       }

.select-color {
          width: 45px;
          height: 45px;
          border-radius: 8px;
          border: 1px solid #c2bebb;
          -webkit-box-shadow: inset 0px -99px 46px -86px rgba(0,0,0,0.42);
          -moz-box-shadow: inset 0px -99px 46px -86px rgba(0,0,0,0.42);
          box-shadow: inset 0px -99px 46px -86px rgba(0,0,0,0.42);
        }

#gold {
          background-color: #f5e7dc;
      }

#silver {
          background-color: #e2e2e2;
        }

#space-grey {
          background-color: #232323;
            }

If anyone has suggestions on a better way to handle this situation, I would greatly appreciate it. Thank you!

Answer №1

To ensure that the width and height of the elements include the border and radius, add box-sizing: border-box to the ul li selector:

ul li {
      width: 47px;
      height: 47px;
      border-radius: 12px;
      border: 2px solid rgba(0,0,0,0);
      padding: 3px;
      box-sizing: border-box;
   }

The use of box-sizing: border-box ensures the total dimensions of the element take into account the border and radius.

Edit:

For further information, here are two links for documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing https://www.w3schools.com/cssref/css3_pr_box-sizing.asp

Answer №2

Utilizing only CSS, this solution involves using radio buttons and labels to achieve the desired effect. Give it a try!

* {
  box-sizing: border-box;
}

.container {
  position: relative;
  padding-top: 30px;
}

label {
  color: transparent;
  position: absolute;
  top: 0;
  left: 0;
}

input:checked+label {
  color: black;
}

input[type="radio"] {
  display: none;
}

#gold+label:after {
  content: "";
  width: 2rem;
  height: 2rem;
  background: gold;
  position: absolute;
  border-radius: 5px;
  top: 30px;
  left: 0;
}

#gold:checked+label:after, #silver:checked+label:after, #bronze:checked+label:after {
  border: 2px solid red;
}

#silver+label:after {
  content: "";
  width: 2rem;
  height: 2rem;
  background: silver;
  position:
   absolute;
  border-radius: 5px;
  top: 30px;
  left: 40px;
}

#bronze+label:after {
  content: "";
  width: 2rem;
  height: 2rem;
  background: sandybrown;
  position: absolute;
  border-radius: 5px;
  top: 30px;
  left: 80px;
}
<div class="container colors">
  <form name="colors">
    <input type="radio" id="gold" name="color" />
    <label for="gold">Gold</label>
    <input type="radio" id="silver" name="color" />
    <label for="silver">Silver</label>
    <input type="radio" id="bronze" name="color" />
    <label for="bronze">Bronze</label>
  </form>
</div>

Answer №4

To maintain the border-color as transparent when the div is not chosen, and modify the border color upon selection. Additionally, consider incorporating a transition effect for added visual appeal.

Answer №5

<style>
        input[type="checkbox"]:checked  ~ #hello{
            box-shadow: 0 0 0 3px hotpink;
        }
        #hello{
            width: 50px;
            margin: 20px;
        }
</style>
<input id="check" type="checkbox">
<label id="hello" for="check">Hello</label>

This code snippet demonstrates how a hidden checkbox can be implemented using CSS and HTML.

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

The issue with res.sendFile is that it is failing to display

I have encountered an issue while attempting to render HTML with res.sendFile using an absolute path. The encoded HTML is being displayed unrendered within a pre tag in the response. Below is the express code I am currently using: app.get('/', ( ...

Importing GeoJSON data into Meteor's Leaflet

Recently diving into Meteor, I am on a mission to create my own customized version of this impressive example from leaflet incorporated into Meteor: Interactive Choropleth Map The implementation requires the use of this GeoJson Data file: us-states The o ...

Looking for a dynamic solution to retrieve over 100 data products in Angular JS? Let's explore methods to efficiently call a large volume of

Just starting out with Angular JS and working on creating a searchable product list gallery using Angular JS. Currently, all my product data is in the same js file which I know isn't the best solution. I would like to make it dynamic by connecting to ...

Obtain the JSON object by provided criteria

In the given JSON data, how can I access an object based on the provided applicationName? { "apps": [ { "applicationName": "myTestApp", "keys": [ { "key": "app-key", ...

Compile a list of URLs found within a particular HTML A tag and save them to a text file

In an attempt to extract specific URLs from a webpage, I aim to target only those within a particular HTML A tag. For instance, the targeted URLs are in HTML A tags that contain "Info science": a bunch of HTML before <a rel="external nofollow&quo ...

Ensure that the divs are properly aligned and construct columns within a single column

I've been working on creating a step bar that needs to adapt to any number of steps provided by the backend. Here's what I have so far: https://i.sstatic.net/cj4qZ.png It looks fine, but connecting the circles with bars would be beneficial. How ...

Incorporating VueJS with a sleek material design aesthetic

Currently, I am in the process of developing a web application using VueJs and am in need of a CSS framework to aid in designing without starting from scratch! After some research, I came across material-design-lite (www.getmdl.io) but unfortunately faced ...

What is the best way to store items in localStorage within Angular version 4.4.6?

I have been working on implementing a basic authentication system in Angular 4.4 with MongoDB as the backend database. login.component.ts import { Component, OnInit } from '@angular/core'; import { AuthService } from 'app/services/auth.ser ...

The Highchart formatter function is being called twice on each occasion

My high chart has a formatter function that seems to be running twice. formatter: function() { console.log("starting formatter execution"); return this.value; } Check out the Fiddle for more details! ...

Stopping PHP execution when an Ajax request is aborted

I want the browser to wait for notifications, but stop waiting if a link is clicked. To achieve this, I have created a PHP script with a while loop that ends when an event occurs and then returns that event. PHP require 'required.php'; ignore_ ...

Looking to construct dynamic checkboxes in Angular by parsing a JSON object retrieved through AJAX

I have a JSON document structured like the example below, and I am looking to generate checkboxes dynamically using Angular. let data = { "Name":[ { "tagId":4489,"name":"Name","label":"Employee Name" } ], "Service":[ { "tagId": ...

The setInterval function will run just one time when triggered by an onclick event

After watching a YouTube tutorial on creating desktop notifications, I had an idea to use it as a reminder tool. For example, having a specific reminder appear as a desktop notification every 30 minutes when triggered by clicking a button. However, the cod ...

The parameter '{ validator: any; }' cannot be assigned to the ValidatorFn type in this context

I am currently experiencing a challenge while attempting to create a custom validator using Angular. I have created a form for my sign-up page and wanted to ensure that the password and confirm password fields match by implementing a custom validator. Des ...

Step-by-step guide on using JQuery to listen to an event and dynamically add a p element after a button, with the feature to remove it on click

I need to implement a functionality where clicking a button will add a new paragraph after the button, and then be able to remove that paragraph by clicking on any word within it. Any guidance on how to achieve this would be highly appreciated. Thank you! ...

Gather information that is dynamic upon the selection of a "li" option using Python Selenium

I need to extract data from this website (disregard the Hebrew text). To begin, I must choose one of the options from the initial dropdown menu below: https://i.stack.imgur.com/qvIyN.png Next, click the designated button: https://i.stack.imgur.com/THb ...

TS1086: Attempting to declare an accessor within an ambient context is not allowed

While using Angular, I encountered the error TS1086: An accessor cannot be declared in an ambient context. when using Javascript getters and setters in this Abstract Typescript class. Here is the code snippet causing the issue: /** * The current id ...

Encountering a Node.js issue when attempting to properly sanitize data before inserting it into MySQL

This is a snippet of code that I am using to insert data into a MySQL table. Before running the query, I escape the values like so: const mysql = require('mysql'); const R = require('ramda'); class Repository { constructor(connectio ...

Having trouble creating a report with an HTML screenshot using Protractor

Need assistance with generating reports using a html screenshot in Protractor. I have followed all the necessary steps but encountered an error. Any help would be appreciated. Here is my conf.js: // Sample configuration file. var HtmlReporter = require(& ...

Increasing the font size on a document

Once again, faced with my own silly problems. This time I stumbled upon the following page: http://jsfiddle.net/g3VBT/ I am trying to style the "enter your U.R.L here" text with the following properties: font-weight: 600; font-size: 1.5em; The issue ...

In search of advice on the best web-based database management technology

I'm looking to create a prototype for a web-based database manager, similar to the desktop version in the image below, with specific features in mind. Initially, the schema will be provided through a flat file. Considering HTML5 as an option, I am a ...