Home > front end >  Stick item in the center of the above item?
Stick item in the center of the above item?

Time:01-02

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 ><img src"https://www.shutterstock.com/image-vector/square-grunge-black-example-stamp-260nw-647778754.jpg></div>
<div ></div>

CodePudding user response:

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 >
    <div >First Container</div>
    <div >Second Container</div>
</div>

CodePudding user response:

You can use flex-box property. Set the display property to flex and use justify-content:center; to center the inside div.

HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>demo</title>
</head>
<body>
<div >
<div >
</div>
</div>
</body>
</html>

CSS:

.container1
{
 display:flex;
 justify-content:center;
}

CodePudding user response:

    .

    wrapper{
          display:flex;
    justify-content: center;
    align-items: center;
        }
        .container-1{
          width: 200px;
          height: 100px;
          background-color: red;
          margin: auto;
        }
        .container-2{
          width: 100px;
          height: 50px;
          background-color: blue;
          margin: auto;
        }
    
    
        <div >
            <div >First Container</div>
            <div >Second Container</div>
        </div>

  • Related