Vertically center a div inside another div

2019-01-25 09:39发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

You can do it this way:

#wrapper {
  border: 1px solid red;
  width: 500px;
  height: 500px;
}
#block {
  border: 1px solid blue;
  width: 500px;
  height: 250px;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Here a live view: https://jsfiddle.net/w9bpy1t4/



回答4:

You can do this:

#block {
border: 1px solid blue;
margin:25% 0;
width: 500px;
height: 250px;
vertical-align: middle;}

But, it's not what you looking for !

or like this:

#wrapper {
border: 1px solid red;
width: 500px;
height: 500px;
display:table-cell;
vertical-align: middle;
}
#block {
border: 1px solid blue;
display:inline-block;
width: 500px;
height: 250px;
}


回答5:

if u know the height of the inner div then u can use position relative on wrapper and position absolute in inner div with some margin. So css can be this

#wrapper {
 border: 1px solid red;
 width: 500px;
 height: 500px;
 position: relative;
 }
#block {
 border: 1px solid blue;
 width: 500px;
 height: 250px;
 vertical-align: middle;
 position: absolute;
 margin-top: 50%;
 top: -125px;
 }