Allison Stafford Allison Stafford - 1 year ago 68
CSS Question

Why do I get a different result from setting translate to -50% and setting margins to 50%?

Assume the parent is relative, the child (style-x) is absolute. I used top 50%, left 25% to center the child.

I wish to actually center the child, so I set transform: translate(-50%, -50%). I am unsure if this is centered, so I double check by deleting that line and adding 'margin-top: -55px;' (half of the height), and 'margin-left: -45px;' (half of the width).

These two lines position my element in slightly different locations, yet this is different from my model of CSS. What's going on?

body {
height: 100%;
width: 100%;
margin: 0 auto;
#main {
overflow: auto;
height: 64vh;
width: 38vw;
margin: 0 auto;
margin-top: 10%;
position: relative;
border: 1vh solid black;
overflow: hidden;
#style-x {
/*Why doesn't translate(-50%, -50%) give me
the same position as setting the margin top and
left to half of the width and height?*/
width: 90px;
height: 110px;
transform: translate(-50%, -50%);*/
margin-top: -55px;
margin-left: -45px;
position: absolute;
top: 50%;
left: 25%;
padding: 2%;
text-align: center;
background: green;
#left-col {
float: left;
width: 4%;
height: 101%;
margin-left: 46%;
background: black;
#right-col {
float: left;
width: 4%;
height: 101%;
margin: 0 auto;
margin-left: 0;
background: black;

<section id='main'>
<div id='style-x'>X</div>
<div id='left-col'></div>
<div id='right-col'></div>

Here's my Codepen if you'd like a visualization.

Answer Source

There is no problem in your method. Both will try to center based on the values you provide.

The margin method fails cos you aren't using a Box Sizing method like so.

box-sizing: border-box

This results in all your elements to be larger than the height and width specified. Without this, you are telling the browser to add any padding or border to both width & height.

And so your larger element shifts when using using the margin method.

You've set a 2% padding on style-x, and a width of 38vw on #main. When using margins to center things, you would need to account for these varying values.

When you set a percentage padding, its calculated based on the width of the containing block.

The transform method on the other hand, uses the bounding box of the containing block and has no problem centering a larger element.

I'd suggest you include this box-sizing on main and style-x if using the margin method. You could just use

*, after, before {
  box-sizing: border-box;

This gives better control over dimensions across all elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download