Center a div in another div when parent div height is undefined
This question already has an answer here:
here's one way to achieve it :)
https://jsfiddle.net/e4xhrvcf/
.parent{
width:500px;
height: 500px;
background-color:red;
display: flex;
align-items: center;
}
如果我明白你想要什么,我想你只需要给父母添加相对位置,以便让孩子在绝对工作中工作:
#parent{
background-color:blue;
width:400px;
height:400px;
position : relative;
}
http://codepen.io/anon/pen/rrdVbO
#parent{
position: relative;
background-color:blue;
width:400px;
height:400px;
}
#child {
position: absolute;
top: 50%;
left: 50%;
background-color:red;
width:50px;
height:50px;
transform: translate(-50%, -50%);
}
The parent needs to have a position
definition for the child's absolute
to work. Use top and left 50% to center the left top corner of the child and transform: translate(-50%, -50%)
to move it back up and left by half of its own height and width.
上一篇: 在父div中垂直对齐div?