I've looked all across this site (and the rest of the internet), and the only question which actually mentions vertically centering two or more is this one, but the only answer there seems to just be an entire code review. In the process of learning CSS, I still cannot reliably position things centrally in the order I want them. Horizontally centering is often just as difficult, although I've managed in the minimal code example below. I know of howtocenterincss.com but that only lets me align one thing vertically.
In the following code example, I want the two buttons collectively to be centered in the div, arranged one above the other, with a margin in between them. I've managed to get half way there, but can't quite figure out how to align them vertically within the div.
#buttonContainer {
display: inline-block;
border: solid 3px black;
width: 400px;
height: 400px;
}
.button {
display: block;
margin: auto;
}
<div id="buttonContainer">
<button id="b1" class="button">Button 1</button>
<button id="b2" class="button">Button 2</button>
</div>
you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%.
To align two <div> elements vertically in Bootstrap 3, you can try using the CSS Flexible Box Layout. In the example below, we display the needed row as a flex container box with the CSS display property and then, align the flex-items (columns) vertically with the align-items property.
Center Align Elements To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
It's not a good idea to apply absolute positioning where you don't want overlapping. You can use flexbox to achieve desired layout. Demo:
#buttonContainer {
/* make element inline flex-container */
/* this will make its children flex-items */
display: inline-flex;
/* align-items items in column */
flex-direction: column;
/* center items horizontally */
align-items: center;
/* center items vertically */
justify-content: center;
border: solid 3px black;
width: 400px;
height: 400px;
}
<div id="buttonContainer">
<button id="b1" class="button">Button 1</button>
<button id="b2" class="button">Button 2</button>
</div>
I usually prefer to use flexbox:
#buttonContainer {
display: flex;
flex-direction: column;
justify-content: center;
border: solid 3px black;
width: 400px;
height: 400px;
}
.button {
display: block;
}
<div id="buttonContainer">
<button id="b1" class="button">Button 1</button>
<button id="b2" class="button">Button 2</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With