【问题标题】:Center absolute div indside/outside relative div中心绝对 div 内部/外部相对 div
【发布时间】:2014-02-26 22:32:37
【问题描述】:

如果你不知道相对 div 的宽度在这种情况下是两者的父元素,是否可以使用 CSS 或 jQuery 将绝对 div 居中在相对 div 内部或外部。

通常我会这样做:

.child {
position: absolute;
top: 100%;
left: -50px;
width: 200px;
height: 300px;
}

但前提是我知道父级是 100px 宽,但如果我不知道怎么办?

FIDDLE

【问题讨论】:

    标签: javascript jquery css positioning


    【解决方案1】:

    如果不需要针对IE8及更低版本,可以使用CSS3calc()函数:

    left: calc(50% - 100px);

    将 100px 替换为您的绝对定位子元素宽度的一半。

    JSFiddle 示例:http://jsfiddle.net/Gmmqh/5/

    注意使用box-sizing: border-box 使盒子彼此均匀,就像第三个一样。

    【讨论】:

    • 我知道,但我不知道父元素的大小应该居中。
    • 你不需要知道父母的大小。您只需要知道绝对定位的子元素的大小并将其除以一半。
    【解决方案2】:

    使用下面的代码将任何内容居中

    margin:0px auto;
    

    所以你的 .child 变成了

    .child {
        display: none;
        position: absolute;
        top: 100%;
        margin:0px auto;
        /*left: -50%;*/
        width: 200px;
        height: 300px;
        background: #eee;
        border: solid 3px #ddd;
    }
    

    【讨论】:

    • 这不适用于绝对定位的元素。
    • 哎呀,很抱歉没有意识到这一点。谢谢。
    猜你喜欢
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多