Home > database >  Div height not consistent based on position
Div height not consistent based on position

Time:11-25

I have folowing demo. These 2 lines should look equal in height, but one is thicker. All this depends on its top position. If I change its top position by 1px it may become "normal" looking again. Is there a way to prevent this behavior?

.a {

  position: absolute;
  top: 0;
}

.line {
  width: 300px;
  height: 1px;
  background: red;
  position: absolute;
  top: 5px;
  box-sizing: border-box;
}

.line2 {
  width: 300px;
  height: 1px;
  background: red;
  position: absolute;
  top: 11px;
  box-sizing: border-box;
}
<div >
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

I can see it on my screen. I think, from looking at the inspector that it's when the calculated height is a few fractions of a pixel out that it sometimes renders as 2 physical pixels high. Moving the height up and down by 1px causes it to behave as desired.

If you just want a 1px solid line you can set the height to 0px and use border-bottom instead.

.a {

  position: absolute;
  top: 0;
  height:11px;
}

.line {
  width: 300px;
  height: 0px;
  background: none;
  border-bottom: 1px solid red;
  position: absolute;
  top: 6px;
  box-sizing: border-box;
}

.line2 {
  width: 300px;
  height: 0px;
  background: none;
  border-bottom:1px solid red;
  position: absolute;
  top: 11px;
  box-sizing: border-box;
}
<div >
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

It happens on Firefox but not on Chrome I have no explanation for why. But the issue here is that the HTML and the Body have 0 heights. Make sure to give them heights. You can test this by forcing and making sure that the parent height has a value of more than 2px. Once I did this the problem is solved.

  • Related