简体   繁体   中英

dock child elements in all corners of parent element

I have the following html5 body:

<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>

And I would like to achieve a dynamic layout that looks this:

块元素对齐

Where as each content element should be layed out (docked) in the corners relative to its parent container and all center elements should be centered at the respective sides. It should not matter what size or position the parent container has, so I cannot use absolute pixel coordinates for positioning.

This is what I have so far:

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;
}

It all works fine for the corners but of course all the center elements are not aligned centered and I understand why. I just don't know, how is this done in CSS3...

To vertically center a fixed-height element in its parent, use:

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

For horizontal you can do the same with left and margin-left, or just not define anything and use "margin:0 auto" since it automatically fills them up equally left and right then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM