skip to Main Content

So I’m struggling to vertically center a div element within another div using CSS.

I’ve tried using various CSS properties like flexbox and vertical-align, which by the way have worked for me before but none of it is working as expected. The element either stays at the top or bottom of the parent container.

PLEASE HELP and thank u in advance 🙂

2

Answers


  1. The approach to achieve the given layout by using flexbox is right. Just add justify-content and align-items parameters for your parent div.
    Here’s the code sample:

    <div class="outer">
      <div class="in">
      </div>
    </div>
    

    CSS

    .outer {
      display: flex;
      justify-content: center; 
      align-items: center; 
    }
    
    
    Login or Signup to reply.
  2. Achieving vertical centering in CSS offers various approaches

    1.

      .parent {
        display: grid;
        place-items: center;
        height: 300px;
        border: 1px solid #000;
      }
    
      .child {
        width: 100px;
        height: 100px;
        background-color: #ccc;
      }
    <div class="parent">
      <div class="child">Center me vertically!</div>
    </div>

    2.

      .parent {
        display: flex;
        justify-content: center; /* Horizontal centering */
        align-items: center; /* Vertical centering */
        height: 300px; /* Just for demonstration */
        border: 1px solid #000; /* Just for demonstration */
      }
    
      .child {
        width: 100px;
        height: 100px;
        background-color: #ccc;
      }
    <div class="parent">
      <div class="child">Center me vertically!</div>
    </div>

    if this is not working then try with position like relative and absolute

    for example

      .parent {
        position: relative;
        height: 300px;
      }
    
      .child {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100px;
        height: 100px;
        background-color: #ccc;
      }
    <div class="parent">
      <div class="child">Center me vertically!</div>
    </div>

    :

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search