physicsboy
physicsboy

Reputation: 6316

Strange outline position when attempting to recreate Chrome <input> outline

I'm making a custom that contains an , and my goal is to remove the natural outline/border from the and place it on the containing such that it still looks natural when focussed, however, it seems that I am not getting the natural outline appearance and instead it looks like the outline is placed on the outside of the div...

Natural input element

enter image description here

My custom div containing the input

enter image description here

Is there something that can be done to achieve the natural outline look?

I have used outline: 5px auto -webkit-focus-ring-color; for the styling on the <div>.

.container {
  display: flex;
  flex-direction: column;
  width: 300px;
}

input, .two {
  font-size: 20px;
  border: 2px solid grey;
  border-radius: 10px;
}

.one {
  margin-bottom: 12px;
}

.two {
  height: 25px;
}

.two:focus-within {
  outline: 5px auto -webkit-focus-ring-color;
}

.three {
  border: 0;
  outline: 0;
  width: 100%;
  background: 0;
}
<div class="container">
  <input class="one" />
  <div class="two">
    <input class="three"/>
  </div>
</div>

Upvotes: 0

Views: 43

Answers (1)

Hao Wu
Hao Wu

Reputation: 20669

You can try giving it a negative outline-offset such as outline-offset: -1px;

It's not pixel perfect, but it does look a bit more like built-in style outline on Chrome:

But do bear in mind that it might vary for different devices. For me -1px looks the best.

.container {
  display: flex;
  flex-direction: column;
  width: 300px;
}

input, .two {
  font-size: 20px;
  border: 2px solid grey;
  border-radius: 10px;
}

.one {
  margin-bottom: 12px;
}

.two {
  height: 25px;
}

.two:focus-within {
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}

.three {
  border: 0;
  outline: 0;
  width: 100%;
  background: 0;
}
<div class="container">
  <input class="one" />
  <div class="two">
    <input class="three"/>
  </div>
</div>


The proper solution might be using box-sizing: border-box;, which border width is also counted for width and height. So you don't need to do anything to make them look identical.

But it seems not working for Safari.

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
  width: 300px;
}

input, .two {
  font-size: 20px;
  border: 2px solid grey;
  border-radius: 10px;
}

.one {
  margin-bottom: 12px;
}

.two {
  height: 30px;
}

.two:focus-within {
  outline: 5px auto -webkit-focus-ring-color;
}

.three {
  border: 0;
  outline: 0;
  width: 100%;
  background: 0;
}
<div class="container">
  <input class="one" />
  <div class="two">
    <input class="three"/>
  </div>
</div>

Upvotes: 1

Related Questions