I'm trying to vertical-align: middle
a div inside another div, but for some reason it's not working properly. What am I doing wrong?
#wrapper {
border: 1px solid red;
width: 500px;
height: 500px;
}
#block {
border: 1px solid blue;
width: 500px;
height: 250px;
vertical-align: middle;
}
<div id = 'wrapper'>
<div id = 'block'> I'm Block </div>
<div>
PS: This is just an example, so no, I don't actually know the actual width and height of the divs, as they are dynamic, according to their contents, so please no margin-top: 125px, or padding-top: 125px answers, or answers like that.
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.
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.
To center a div vertically and horizontally using flexbox, you need to wrap the div or div's inside a container with properties ' display: flex; flex-direction: column; justify-content: center;align-items: center; ', then just make the div ' text-align: center; ' if it has text.
The vertical-align
property applies only to inline-level and table-cell elements (source). In your code you're working with block-level elements.
Try this flexbox alternative:
#wrapper {
border: 1px solid red;
width: 500px;
height: 500px;
display: flex; /* establish flex container */
align-items: center; /* vertically center flex items */
}
#block {
border: 1px solid blue;
width: 500px;
height: 250px;
/* vertical-align: middle; */
}
<div id='wrapper'>
<div id='block'> I'm Block </div>
<div>
Learn more about flex alignment here: Methods for Aligning Flex Items
Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.
Here is how I normally do this.
#wrapper {
border: 1px solid red;
width: 500px;
height: 500px;
position: relative;
}
#block {
border: 1px solid blue;
width: 500px;
height: 250px;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
<div id="wrapper">
<div id="block"></div>
</div>
Easy way to make it dynamic.
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