CSS vertical-align property doesn't work

可紊 提交于 2019-12-10 15:57:13

问题


Hey there I have the following CSS code:

.parent
{
    position : 'absolute';
    top : '50px';
    left : '50px';
    width : '400px';
    height : '160px';
    padding : '10px';
    border : '2px solid';
    border-color : '#444444';
    background-color : '#FF0000';
    text-align : 'center';
    /*display : inline; tried this also and didn't work.*/
}

.child
{
    color : '#123456';
    font-size : '16px';
    font-family : 'Arial';
    vertical-align : 'middle';
}

I just want to put the child's content in the center (x and y) of the parent div, but it's not working, it only shows me the text in the top side of the parent element. Any suggestion? thank you.


回答1:


vertical-align has a deceiving name. It doesn't actually vertically align elements in the way that you think it does.

If your child has only one line of text, you can use the line-height trick to center it:

.parent {
    line-height: 160px; /* Height of the parent */
}

Demo: http://jsfiddle.net/vVAdZ/

Another way is to fake a table:

.parent {
    display: table;
}

.child {
    display: table-cell;
    vertical-align: middle;
}

Demo: http://jsfiddle.net/vVAdZ/3/




回答2:


Lose the quotes in your CSS property values and add line-height: 160px; to .parent




回答3:


Take whatever the width is, which in this case is 400, and divide by 2 for half of the div. Then take half of the height 160, and divide by 2 for half the height, and you should get the center.



来源:https://stackoverflow.com/questions/16205907/css-vertical-align-property-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!