gpt4 book ai didi

css - 为什么将转换设置为 -50% 并将边距设置为 50% 会得到不同的结果?

转载 作者:行者123 更新时间:2023-11-28 16:04:37 25 4
gpt4 key购买 nike

假设父项是相对的,子项 (style-x) 是绝对的。我使用前 50%,剩下 25% 来让 child 居中。

我希望实际上让 child 居中,所以我设置了 transform: translate(-50%, -50%)。我不确定这是否居中,所以我通过删除该行并添加 'margin-top: -55px;' 来仔细检查(高度的一半)和'margin-left: -45px;' (宽度的一半)。

这两行将我的元素定位在略有不同的位置,但这与我的 CSS 模型不同。怎么回事?

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;
}
<body>
<section id='main'>
<div id='style-x'>X</div>
<div id='left-col'></div>
<div id='right-col'></div>
</section>
</body>

如果你想要可视化,这是我的 Codepen。

http://codepen.io/sentedelviento/pen/ORyqzv

最佳答案

你的方法没有问题。两者都会尝试以您提供的值为中心。

margin 方法失败,因为您没有使用 Box Sizing method像这样。

box-sizing: border-box

这会导致所有元素 大于指定的高度和宽度。如果没有这个,您就是在告诉浏览器为宽度和高度添加任何填充或边框。

因此,当使用边距方法时,您的较大的元素会移动。

您已经设置了一个 2%填充 style-x , 宽度为 38vw#main .使用边距居中时,您需要考虑这些不同的值

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

另一方面,transform 方法使用包含 block 的边界框,并且可以将较大的元素居中。

我建议您包括这个 box-sizingmainstyle-x如果使用 margin 方法。你可以只使用

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

这可以更好地控制所有元素的维度。

关于css - 为什么将转换设置为 -50% 并将边距设置为 50% 会得到不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39443654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com