Home > front end >  1px wide element looks thicker than a border of 1px width
1px wide element looks thicker than a border of 1px width

Time:07-18

I created a box and gave it a border that is 1px wide. I wanted to add a line that goes across it from the top left corner to the bottom right corner, so I used a pseudo element and gave it a height of 1px and a width that is large enough to make it span the entire the box at a 45 angle. The problem is that the line turned out to be much thicker than the border, even though they have the same dimension of 1px.

.box {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  position: relative;
  overflow: hidden;
}

.box::before {
  content: '';
  display: block;
  width: 141.4213562px;
  height: 1px;
  background-color: black;
  position: absolute;
  top: 0;
  left: 0;
  transform: rotate(45deg);
  transform-origin: 0 0;
}
<div ></div>

CodePudding user response:

It only looks thicker due to the pixelation from being diagonal. In the snippet, hover the first box you will see the lines rotate and appear as thick as the border.

Only way I can think to fix is by making the lines less than 1px thick as can be seen on the second box. This will render slightly differently based mostly on the quality of the screen, elements/borders less than 1px can appear very feint on older screens. I've added a bit of a box-shadow here in an attempt to thicken the line slightly and anti alias it

:root { --borderThickness: 1px }

.boxes { display: flex; gap: 1rem; justify-content: center }

.box {
  border: var(--borderThickness) solid currentColor;
  display: grid;
  height: 100px; width: 100px;
  overflow: hidden;
  place-items: center;
  position: relative;
}

.box::before, .box::after {
  background-color: currentColor;
  content: '';
  grid-area: 1/1/-1/-1;
  height: var(--borderThickness); width: 141.4%;
  transform: rotate(var(--rotate));
  transition: transform 120ms ease-in-out;
}

.box::before { --rotate: 45deg } .box:hover::before { --rotate: 90deg }
.box::after { --rotate: -45deg } .box:hover::after { --rotate: 0deg }

.box.fix::before, .box.fix::after {
  height: calc(var(--borderThickness) / 1.414 );
  box-shadow: 0 0 0.25px calc(var(--borderThickness) / 10 ) currentColor; /* Thicken line and anti alias */
}
<div >
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

it seems like a optical illusion, you can change the color of slash line.

  • Related