skip to Main Content
.container{
  position:fixed;
  width:100%;
  aspect-ratio:1;
  top:0;
  left:0;
  display:grid;
  place-items:center;
}
.outer{
  position:absolute;
  width:200px;
  aspect-ratio:1;
  border:5px solid gold;
}
.inner{
  position:absolute;
  width:100px;
  aspect-ratio:1;
  border:5px solid gold;
}
<div class="container">
<div class="outer">
<div class="inner"></div>
</div>
</div>

I am trying to stack the inner and outer div directly ontop each other,so the inner div would be at the center of the outer div, while centering the parent div fixed horizontally and vertically on the webpage

2

Answers


  1. Here I try to fix the inner div position in the center, while the parent div keeps both vertical and horizontal center!

    html,
    body,
    .container {
      height: 100%;
    }
    
    .container {
      position: fixed;
      width: 100%;
      aspect-ratio: 1;
      top: 0;
      left: 0;
      display: grid;
      place-items: center;
    }
    
    .outer {
      position: absolute;
      width: 200px;
      aspect-ratio: 1;
      border: 5px solid gold;
    }
    
    .inner {
      position: absolute;
      width: 100px;
      aspect-ratio: 1;
      border: 5px solid gold;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    <div class="container">
      <div class="outer">
        <div class="inner"></div>
      </div>
    </div>
    Login or Signup to reply.
  2. Flexbox is useful for centering.

    html, body, .container {
      height: 100%;
    }
    body {
      margin: 0;
    }
    .container, .outer {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .outer{
      width: 200px;
      aspect-ratio: 1;
      border: 5px solid gold;
    }
    .inner{
      width: 100px;
      aspect-ratio: 1;
      border: 5px solid gold;
    }
    <div class="container">
    <div class="outer">
    <div class="inner">
    </div>
    </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search