skip to Main Content

What is the best way to position a horizontally centered element at the top, a horizontally centered at the bottom and an element at the center of the screen?Layout

3

Answers


  1. You need to set the height of the html and body to 100%, then use flexbox with flex-direction: column; to make it operate vertically, and justify-content: space-between; to do the spacing.

    html, body {
      height: 100%;
    }
    body {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      margin: 0;
    }
    body>* {
      border: 1px solid lime;
    }
    <body>
      <div>Element 1</div>
      <div>Element 2</div>
      <div>Element 3</div>
    </body>
    Login or Signup to reply.
  2. To horizontally align center a block element (like paragraph inside div) as well as Text, use margin: auto;

    <style>
    .center {
      margin: auto;
      width: 60%;
      border: 3px solid #73AD21;
      padding: 10px;
    }
    .centerText {
      text-align: center;
      border: 3px solid green;
    }
    </style>
    
    <div class="center">
      <p>This Element is Aligned Horizontally Center !</p>
    </div>
    
    <div class="centerText">
      <p>Hello World!</p>
    </div>
    
    
    Login or Signup to reply.
  3. The display: grid can also be used to attain the desire. Grid-Template-Rows and Grid-Template-Columns can be used to set the appropriate size for each row and column, respectively. In this case, the fractional unit Fr stands for one part of the available space (1fr). For more information on fr, visit this page.

    <style>
            html,body{height: 100%;}
            .wrapper {
                display: grid;
                grid-template-columns: repeat(1, 100px);
                grid-template-rows: repeat(3, 1fr);
                height: 100%;
                width: 100%;
                grid-gap: 20px;
                align-content:space-between;
                justify-content: space-around;
              }
            
              .item1{
                background-color:green ;
              }
    
              .item2{
                background-color: blue;
              }
    
              .item3{
                background-color: blueviolet;
              }
              
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div class="item1">Item 1</div>
            <div class="item2">Item 2</div>
            <div class="item3">Item 3</div>
          </div>
    </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search