Search code examples
htmlcssborder

How to prevent div elements from moving when border is applied to div?


I am currently working on a div element containing a radio button and a label. It looks like this:

enter image description here

When hovering over the div element, I am applying a border to that div so the result looks like this:

enter image description here

The problem here is, that the moment the border is visible, you can see that the elements move 2px down and right because of the border size. The border size is 2px.

How can I prevent this from happening?

Here is the relevant css I am using:

.container {
  display: inline-flex;
  align-items: center;
}

.label {
  display: inline-block;
  margin-top: 0;
  margin-right: 0;
  margin-bottom: 0;
  margin-left: 15px;
}

.radioButton {
  width: 18px;
  height: 18px;
  padding: 0;
  border: 2px solid white;
  margin: 0;
  appearance: none;
  background-color: #fff;
  border-radius: 100%;
  box-shadow: 0 0 0 2px #002750;
  transition: all ease-in 0.2s;
}

.radioButton:checked {
  background-color: #002750;
}

.radioButton:focus,
.radioButton:hover {
  box-shadow: 0 0 0.15em 0.2em #0c64e7;
}

.container:focus,
.container:hover {
  border-width: 2px;
  border-style: solid;
  border-color: #419BF9;
  border-radius: 15px 5px 5px 15px;
}
<div class="container">
  <input type="radio" class="radioButton">
  <label class="label">Copy</label>
</div>

I appreciate every help!


Solution

  • The easiest solution is to provide a transparent border to the div that you are adding a border to when hovering.

    .container {
      display: inline-flex;
      align-items: center;
      border: 2px solid transparent;
    }