css - 在 div 中以绝对位置居中两个容器

标签 css html center

使用 CSS,我想将一个 div 中的两个“框”水平居中。盒子是绝对定位的。

这是 JSFiddle:http://jsfiddle.net/p4sA3/8/

如果不使用特定宽度,我如何实现这一目标?

HTML:

<button id="change">Change</button>
<div id="total-wrap">
    <div id="hello-wrap" class="bunch">
        <div id="box"> 
            <p> Hello, this is text1 </p>
        </div>
        <div id="box">
            <p> Hello, this is text2 </p>
        </div>
    </div>
    <div id="goodbye-wrap" class="bunch">
        <div id="box"> 
            <p> Goodbye, this is text1 </p>
        </div>
        <div id="box">
            <p> Goodbye, this is text2 </p>
        </div>
    </div>
</div>

CSS:

#total-wrap {
    border:1px solid #000;
    height:500px;
}
#box {
    position:relative;
    display:inline-block;
    width:300px;
    height:100px;
    background-color:yellow;
    margin:10px;
}
.bunch {
    position: absolute;
    text-align:center;
}

最佳答案

我会用 left:0;right:0 来做,因为它们是绝对定位的。

演示 http://jsfiddle.net/kevinPHPkevin/p4sA3/19/

.bunch {
    position: absolute;
    text-align:center;
    left:0;
    right:0;
}

关于css - 在 div 中以绝对位置居中两个容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16753055/

相关文章:

html - 将一个 css 文件连接到多个 html 页面

javascript - DIV的onclick中的alert()点击后不显示

javascript - 嵌入文档时不需要的页面边框

javascript - 响应式 CSS : div too big

css - 在选项卡中环绕居中文本

javascript - 为什么在我调整浏览器大小时我的 div 会重叠?

css - 如何将CSS3动画绑定(bind)到类

html - 输入类型="number"是否只从html5开始有效?

css - 使用 CSS 在父 div 中居中任意数量的 div

jquery - 用 jQuery 居中 div