Home > database >  Center a text box and button perfectly using bootstrap 5
Center a text box and button perfectly using bootstrap 5

Time:10-10

I have the following html using bootstrap 5:

<div style="margin-top: 30%" >
    
    <h1>Let's get started...</h1>

    <input id="form-input" style="display: inline-block;" type="text"  placeholder="Search for a prefix" />

    <button id="form-button" type="submit" >Find Numbers</button>

</div>

This is the result in a browser:

enter image description here

How can I make sure they are exactly the same height, and if the browser is made too small, the submit button will drop beneath the input

CodePudding user response:

Honestly I did not quite understand your goal, so excuse me if my answer is wrong. You can user screen.width to make the submit button will drop beneath the input.

let width = screen.width;
if(width > // any number you want) {
    document.getElementById('form-input').style = 'display: block; margin-left: X px'
}

And for the same height you can use position: relative; and position: absolute:

div {
    positon: relative;
}
 
input,
button {
    positon: absolute;
    top: 0;
}

Hope this helps.

CodePudding user response:

You need to wrap them with flex parent like this:

<div style="margin-top: 30%" >
<h1>Let's get started...</h1>
<div >
  <input id="form-input" style="display: inline-block;" type="text"  placeholder="Search for a prefix" />
  <button id="form-button" type="submit" >Find Numbers</button>
</div>

and adjust the width for the small screen (I'd suggest using col-lg-* but you are using form-control so it has 100% width):

.form-control {
  width: 25%;
}
@media(max-width: 767px) {
  .form-control {
     width: 80%;
     margin-bottom: 20px;
  }
}
  • Related