bad pixel bad pixel - 1 year ago 105
CSS Question

Place one div under another div in this code sample

I am playing around with this code on codepen and I am trying to place text, under the animated circle and centered in the viewport, but I cannot seem to find a way to do it. I have set

background: yellow;
on the text for visibility.

If you know why the solution works, it would be immensely helpful if you could explain it here for me to understand/learn.

Answer Source

if you use flex, then apply it on HTML so body can shrink on content. margin-left:-50%; will be efficient and can be used to center one element.

For vertical-align, you may use (either) display : inline-block/inline-table + vertical-align:middle in order to center 2 elements being side by sides.

basicly, your CSS template can become

html {
    height: 90%;
    background: #c2c2c2;
    display: flex;
    align-items: center;
    justify-content: center;

body {margin:0;}

.text {
    background: yellow;
    display: inline-table;/* or inline-block to vertical align */
    vertical-align: middle;
    margin-left: -50%;/* body flex-child takes width of content, not window ;) */
    position: relative;/* bring it up front , add z-index too if needed */

.spinner {
    display: inline-block;/* not a flex-child anymore & float doesn't allow vertical-align */
    vertical-align: middle;/* says itself */
    width: 300px;
    height: 300px;
    min-width: 300px;
    position: relative;
    animation: spin 60s linear infinite;

... and render -> screen shot

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download