简体   繁体   中英

CSS3 translate: using percent values

I'm attempting to understand why in this codepen the two boxes aren't perfectly aligned.

https://codepen.io/mburke05/pen/BYXOGP

html

<div class="div_one">pixel</div>
<div class="div_two">percent</div>

css

.div_one {
  border: solid red;
  transform: translate(70px, 20%) ;
  width: 140px;
  height: 60px;
}

.div_two {
  border: solid blue;
  transform: translate(50%, 30%) ;
  width: 140px;
  height: 60px;
}

I thought I understood that, when using %'s rather than pixel or other values, that the % value was based on the height of the element itself rather than the % of the parent (which in this case would be the viewport.)

However, to achieve what I believe is alignment, I would need to set translate(48%, 30%) as the value. Why is this? Isn't 70 50% of 140, or is there more to it than I'm understanding.

As a follow-up, can anybody explain why this is the preferred way of centering an object vertically mathematically?

div {
  box-sizing : border-box
}

By default in the CSS box model, the width and height you assign to an element is applied only to the element's content box. If the element has any border or padding, this is then added to the width and height to arrive at the size of the box that's rendered on the screen. This means that when you set width and height you have to adjust the value you give to allow for any border or padding that may be added.

Read More here

.div_one {
  border: solid red;
   width: 140px;
  height: 60px;
}

.div_two {
  border: solid blue;
  width: 140px;
  height: 60px;
}

remove CSS property "transform", Both Div will align perfectly and if you want to move the position of the box means use padding or margin and if you want to fix in box position then use Position property

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM