Search code examples
htmlcssflexboxalignmentcss-position

Stick item in the center of the above item?


How can I center an item in the center of another item?

Visual representation:

 [   .   ]     (not centered random item = container-1)
    [.]        (item horizontally centered in relation to the item above = container-2)


<div class="container-1"><img src"https://www.shutterstock.com/image-vector/square-grunge-black-example-stamp-260nw-647778754.jpg></div>
<div class="container-2"></div>

Solution

  • You could use a wrapper div for both elements and given both margin:auto to align them within the wrapper container, and provide the wrapper class the alignment you require for the first container.

    Alternatively you could give the wrapper class a flex display, flex-direction column, and align-items to center, and provide the required alignment for the first container to the wrapper class.

    /*Say I wanted the first container to positioned 5px from the left of the window. I'd provide this alignment to the wrapper class.*/
    .wrapper{
      position: absolute;
      left: 5px;
    }
    .container-1{
      width: 200px;
      height: 100px;
      background-color: red;
      margin: auto;
    }
    .container-2{
      width: 100px;
      height: 50px;
      background-color: blue;
      margin: auto;
    }
    <div class="wrapper">
        <div class="container-1">First Container</div>
        <div class="container-2">Second Container</div>
    </div>