Home > Back-end >  centering a div or input element vertically using bootstrap
centering a div or input element vertically using bootstrap

Time:07-06

https://i.stack.imgur.com/2OHp2.png

My code rn:

<body >
        <div >
            <div >
                <input  list='datalistOptions' placeholder="Where would you like to travel?">
            </div>
            <div >
                <button  id="btn">Search</button>
            </div>
        </div> 
</body>

CodePudding user response:

Add align-items-center and min-vh-100 with your row

CodePudding user response:

This fixed it for me:

<body >
        <div >
            <div >
                <input  list='datalistOptions' placeholder="Where would you like to travel?">
            </div>
            <div >
                <button  id="btn">Search</button>
            </div>
        </div> 
</body>

CodePudding user response:

You need to add align-items-center and min-vh-100 to your row. Like this:

<body >
 <div >
  <div >
   <input  list='datalistOptions' placeholder="Where would you like to travel?">
  </div>
  <div >
   <button  id="btn">Search</button>
  </div>
 </div> 
</body>

CodePudding user response:

There are a few ways you can achieve this. But let's take a look at how it is done in CSS and compare it to the utility classes in Bootstrap.

Considering we have the following HTML

<div >
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
</div>

Solution with CSS Flex

.parent {
  display: flex;

  /* Center Horizontally */
  justify-content: center;
  
  /* Center Vertically */
  align-items: center;
}

Solution with Bootstrap Flex Utilities

<div >
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
</div>

Solution with CSS Grid

.parent {
  display: grid;
  
  /* Center both vertically and horizontally */
  place-items: center;
}

Solution with Bootstrap Grid Utilities. Unfortunately, there is no class for place-items-center. Therefore, you can use inline styles

<div  style="place-items:center">
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
</div>

Bear in mind that for you to be able to center anything in the middle of the screen, you'll have to define a height to the parent. If you are using any block level element such as div the width is already 100%. But the height will always follow the content. In the screenshot you shared, it seems like you want to center it in the middle of the screen. For that you'll have to add vh-100 (View Height 100) to the parent to have it expand to the full height of the screen.

  • Related