I have a div containing some content. It has a height of 31px and inside it, the button has smaller height.
<div class="headerAndButton">
<h3 class="h3">
Click the button to the right
<button>click me</button>
</h3>
</div>
I have another header that does not have a button in it.
<div class="headerAndButton">
<h3 class="h3">No button here, I only want to have this header have the same vertical alignment, height and margin as the other header</h3>
</div>
I want to vertically align the <h3>
text within each div. I have tried to solve the problem with the following SCSS:
.headerAndButton {
margin-bottom: $space-300;
h3 {
min-height: 31px;
vertical-align: bottom;
button {
margin-left: $space
}
}
}
The vertical-align
property has no visible effect. The text in the without the botton is top aligned. The text in the other is a bit lower. It also becomes top aligned if I remove the button.
How can I make this headers have the same vertical alignment? I am not good at CSS, so maybe there are completely different better ways to solve this.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.
For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.
You could use several methods to vertical align an element. For example you could use new display: flex
methods:
display: flex;
justify-content: center;
flex-direction: column;
Example
If its no problem to position: absolute
your element you could use
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
There is a quite good tutorial from CSS-Tricks, named Centering in CSS: A Complete Guide.
display: flex;
justify-content: center;
align-items: center;
just apply this CSS code on headerAndButton
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