【问题标题】:dock child elements in all corners of parent element将子元素停靠在父元素的各个角落
【发布时间】:2013-04-12 22:07:14
【问题描述】:

我有以下 html5 正文:

<body>
    <div id="container">
        <div class="content" id="topleft">topleft</div>
        <div class="content" id="topcenter">topcenter</div>
        <div class="content" id="topright">topright</div>
        <div class="content" id="centerleft">centerleft</div>
        <div class="content" id="centercenter">centercenter</div>
        <div class="content" id="centerright">centerright</div>
        <div class="content" id="bottomleft">bottomleft</div>
        <div class="content" id="bottomcenter">bottomcenter</div>
        <div class="content" id="bottomright">bottomright</div>
    </div>
</body>

我想实现如下所示的动态布局:

每个内容元素应相对于其父容器布置(停靠)在角落中,并且所有中心元素应在各自侧面居中。父容器的大小或位置无关紧要,因此我不能使用绝对像素坐标进行定位。

这是我目前所拥有的:

div#container {
    background: lightblue;
    position: relative;
    width: 500px;
    height: 500px;
}

div.content
{
    width: 100px;
    height: 100px;
    position: absolute;
    background: lightyellow;
    text-align: center;
    margin: auto;
}

div#topleft {
}

div#topcenter {
    right: 50%; /*obviously doesn't center*/
}

div#topright {
    right: 0px; 
}

div#centerleft {
    top: 50%; /*obviously doesn't center*/
    left: 0px;
}

div#centercenter {
    top: 50%; /*obviously doesn't center*/
    right: 50%; /*obviously doesn't center*/
}

div#centerright {
    right: 0px;
    top: 50%; /*obviously doesn't center*/
}

div#bottomleft {
    bottom: 0px;
}

div#bottomcenter {
    bottom: 0px;
    right: 50%; /*obviously doesn't center*/
}

div#bottomright {
    right: 0px;
    bottom: 0px;
}

这一切都适用于角落,但当然所有中心元素都没有居中对齐,我明白为什么。我只是不知道,这是如何在 CSS3 中完成的......

【问题讨论】:

    标签: html css layout


    【解决方案1】:

    要在其父元素中垂直居中固定高度的元素,请使用:

    top:50%;
    margin-top:-50px;
    

    对于水平,您可以对 left 和 margin-left 执行相同的操作,或者不定义任何内容并使用“margin:0 auto”,因为它会自动将它们左右相等地填充。

    【讨论】:

    • 谢谢!这很容易#facepalm!
    • 还有一件事:如果内容 div 没有固定大小怎么办?
    • 有一些方法,但它们很讨厌。一般来说,尽量避免它,垂直居中的灵活大小的内容通常是滥用 HTML 的基于流的范例的标志。使用 display:table-cell 可以解决一些问题,但可能会引入新问题。
    猜你喜欢
    • 2013-01-03
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多