overflow:hidden on inline-block adds height to parent

不羁岁月 提交于 2019-11-28 19:45:52

问题


I'm certain this has been asked before in some form or other, but I just can't find an answer..

I have some nested divs

<div class="parent">
    <div class="child">A</div>
</div>

And the child has display:inline-block and overflow:hidden

.parent{
    background-color:red;
}
.child{ 
    background-color:green; 
    display:inline-block;
    overflow:hidden; 
}

And it gets rendered like this:

You can notice that the parent is 5px higher than the child.

Where does the extra height come from?

Here is the sample: http://jsfiddle.net/w8dfU/

Edit: I don't want to remove display:inline-block or overflow:hidden, this is a simplified example to illustrate the problem, but in my real layout I need them both. I just want to understand why this extra height appears. Is it specified somewhere that it should be like this? Is it a consequence of some other css feature?


回答1:


I had this issue when building a horizontal slider. I fixed it with vertical-align:top on my inline-block elements.

ul {
    overflow-x: scroll;
    overflow-y:hidden;
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;
}

ul&::-webkit-scrollbar {
    display: none;
}

li {
    display: inline-block;
    vertical-align: top;
    width: 75px;
    padding-right: 20px;
    margin:20px 0 0 0;
}



回答2:


The accepted answer above is correct, but it does not give the explanation I was looking for. A good explanation was provided by @Alohci in his comment.

Explanation in a few words:

  • The value for vertical-align is baseline, therefore the child div is aligned with the baseline of the text.

  • This text baseline is not the same as the bottom line. It's a bit higher up, to accommodate letters with descenders: p, q, g.

  • This is why the problem is fixed by setting vertical-align:top.




回答3:


.child{
    background-color:green; 
    display:inline-block;
    overflow:hidden; 
    vertical-align: top;
}



回答4:


This extra space coming from overflow:hidden of Child class. Remove this property and check and if your really wanted to use overflow:hidden property then use negative margin to child class . You can remove this extra space.



来源:https://stackoverflow.com/questions/20310690/overflowhidden-on-inline-block-adds-height-to-parent

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