css – 如何将子元素从其父元素的中心垂直偏移?

作者:互联网

2026-04-07

HTML教程
Here是我设置的jsFiddle.

父元素和子元素的高度将是不确定的(意味着它将在之后改变)并且子元素的位置必须是绝对的.

如何将子元素从父级中心垂直偏移五个像素?

HTML:

CSS:

.parent{    position:relative;    margin: 10% auto;    background:lightgray;    height:50px;/*parent's height will change after*/    width:200px;}.parent .child{    position:absolute; /* needs to be absolutely position */    top:0;    bottom:0;    margin:auto;    width:100%;    height:20px;/*child's height will change after*/    background:darkgray;}
偏移5px在哪里?

像这样—-> Updated Fiddle

要么

像这样—-> Updated Fiddle