gpt4 book ai didi

html - CSS3 : translateX to center element horizontally

转载 作者:太空宇宙 更新时间:2023-11-04 13:33:47 24 4
gpt4 key购买 nike

我试图将一个元素水平居中:jsfiddle

<div id="parent">
<div id="child">
</div>

在 child 身上,我现在有以下不居中的 css:

transform: translateX(50%);

不幸的是,50% 是从#child 而不是 parent 那里拿走的。有没有一种方法可以使用变换将此元素居中(我知道我可以使用“左”等方式将其居中)?

这里是css的完整 list

#parent {
width: 300px
height: 100px;
background-color: black;
border: 1px solid grey;
}
#child {
height: 100px;
width: 20px;
-webkit-transform: translateX(50%);
background-color:red;
}

最佳答案

您缺少父级的相对位置、子级的绝对位置以及有助于抵消子级的 left 和 top 值。

演示 http://jsfiddle.net/nA355/6/

#parent {
width: 300px;
height: 100px;
background-color: black;
border: 1px solid grey;
position: relative;
}
#child {
position: absolute;
height: 100px;
width: 20px;
left: 50%;
top: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
background-color:red;
}

关于html - CSS3 : translateX to center element horizontally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20538718/

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