Why is my checkbox not vertically aligned in it

2019-08-28 16:40发布

问题:

This question already has an answer here:

  • How to center div vertically inside of absolutely positioned parent div 9 answers

I have a checkbox with this css code:

.row-checkbox {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -12px;
  margin-top: -9px;
}

It's parent is a element with position: relative;. I'm having problems vertically centering the checkbox in Edge browser (in chrome works fine). It seems that the top:50% isn't working in either browsers, but something in chrome still makes it centered.

I don't want to change make a big change like changing to flex because I have these elements all over my project, I would just want to add a fix to support Edge.

I've been trying to solve it for hours now, a lot of things that didn't work.

回答1:

Instead of

margin-left: -12px;
margin-top: -9px;

just use a transformation:

transform: translate(-50%, -50%);

This (along with position: absolute; top: 50%; left: 50%; and a positioned parent) is a universal approach of centering any element regardless of its height and width.