css 左:50%元素未出现在页面中间

rn0zuynd  于 2023-01-06  发布在  其他
关注(0)|答案(6)|浏览(201)

我有一个绝对定位弹出窗口(悬停在“冰白色”图像看到弹出窗口),其中有CSS左:50%。现在这应该出现在页面中间,但没有。任何建议,请?提前感谢。

dffbzjpn

dffbzjpn1#

你还应该把margin-left和元素可见宽度的一半的负数相加,例如:

width: 400px;
padding: 10px;
border-width: 2px;
/* -(400 + 10 + 2)/2 = -206 */
margin-left: -206px;
left: 50%;

注意,其他人建议的margin: auto不起作用,因为您已经绝对定位了元素。

k5hmc34c

k5hmc34c2#

position: absolute;
 left: 50%;
 transform: translate(-50%,0)
unftdfkk

unftdfkk3#

哈哈,不。图片的左边只占页面宽度的50%。因此;* 左:50%*。
要使图像居中,请设置 * 边距:自动 *。

e4yzc0pl

e4yzc0pl4#

您的代码工作正常。弹出窗口被放置在其嵌套的TD标记的50% ...左侧。
尝试将弹出窗口从表格中删除,或者将其设置为文档宽度的50%(您的javascript缩小了,我无法阅读,否则我会进一步帮助您)。

vsnjm48y

vsnjm48y5#

你可以尝试改变CSS样式像这样

#displayDiv {
    background-color: white;
    font-weight: bold;
    height: 460px;
    left: 50%;
    margin: auto auto auto -475px;/* change done here */
    overflow: hidden;
    position: absolute;
    text-align: center;
    top: 80px;
    width: 950px;
    z-index: 1;
}
wljmcqd8

wljmcqd86#

在我看来,在"冰白色"图像和正文之间的某个地方有一个包含元素(具体来说,Firebug显示它是<a class="popup1" ... >),这是相对定位的,所以你的50%是相对于 * 那个 * 而不是整个页面的。
我知道这看起来有点违反直觉:如果poput使用 * absolute * 定位,为什么它应该是相对于父元素的?这基本上是因为相对定位是相对于元素在文档的正常 * flow * 中的位置,而绝对定位是将元素从该流中拉出来。更多信息请参见the W3C's explanation of the visual formatting model的9.4.3和9.6节。
Check out a tutorial or two if this is giving you trouble. I like Learn CSS Positioning in Ten Steps and css-tricks.com's "Absolute Positioning Inside Relative Positioning" (to which I'd provide a link if not for the spam filter; first-time answerer here ;) ).
至于该怎么做,您也许可以像mblaze75建议的那样,将弹出窗口从相对定位的父对象中移出,但看起来(我在这里猜测)<a>似乎是触发JavaScript事件的原因,因此您可能无法这样做。相反,我会尝试删除相对定位,并使用边距来代替。
另外,请记住格雷格·阿格纽的话:即使这个问题解决了,你仍然把弹出窗口的左边缘居中,而不是居中,我想duri的答案会解决这个问题。

相关问题