内联块<div>在父级之外被推下,高度超过父级,尽管高度:inherit; </div>

时间:2014-08-22 10:18:33

标签: html margin padding css

问题

  1. .nav-item <div>的高度高于其父级 - 尽管height: inherit;
  2. 尽管没有任何边距或填充,.nav-item <div>会被推到父母之外。
  3. HTML

    <div id="nav">
        <h1>A website</h1>
        <div class="nav-item">
            <p>Item 1</p>
        </div>
        <div class="nav-item">
            <p>Item 2</p>
        </div>
        <div class="nav-item">
            <p>Item 3</p>
        </div>
    </div>
    

    CSS

    #nav {
        height: 75px;
        left: 0;
        right: 0;
        top: 0;
        margin: auto;
        position: fixed;
        background-image: url('img/gradient.png');
        padding: 0;
    }    
    
    #nav h1 {
        top: 8px;
        margin-left: 15px;
        margin-right: 15px;
        position: relative;
        font-size: 42px;
        font-family: 'Francois One', Impact, Futura, sans-serif;
        color: rgb(255,255,255);
        display: inline;
    }
    
    #nav .nav-item {
        display: inline-block;
        height: inherit;
        padding: 10px;
        margin: 0;
        background: blue;
    }
    
    #nav .nav-item p {
        font-family: 'Francois One', Impact, Futura, sans-serif;
        margin: 0;
    }
    

    结果

    Screenshot 1 Screenshot 2 Screenshot 3

3 个答案:

答案 0 :(得分:1)

这里发生的是预期的。高度不会继承,由text-alignmentpaddingmargin宽度计算。请这样做:

  1. 删除padding顶部和底部。
  2. 删除margin顶部和底部。
  3. vertical-align: top;添加到.nav-item s。
  4. 解决方案

    CSS

    #nav .nav-item {margin: 0; padding: 0 10px; vertical-align: top;}
    

    预览:

    小提琴:http://jsfiddle.net/praveenscience/vnfdv9bj/

答案 1 :(得分:0)

vertical-align:topbox-sizing:border-box添加到.nav-item

&#13;
&#13;
#nav {
    height: 75px;
    left: 0;
    right: 0;
    top: 0;
    margin: auto;
    position: fixed;
    background-image: url('img/gradient.png');
    background:#ff00ff;
    padding: 0;
}    

#nav h1 {
    top: 8px;
    margin-left: 15px;
    margin-right: 15px;
    position: relative;
    font-size: 42px;
    font-family: 'Francois One', Impact, Futura, sans-serif;
    color: rgb(255,255,255);
    display: inline;
}

#nav .nav-item {
    display: inline-block;
    height: inherit;
    padding: 10px;
    margin: 0;
    background: blue;
    vertical-align:top;
    box-sizing:border-box;
}

#nav .nav-item p {
    font-family: 'Francois One', Impact, Futura, sans-serif;
    margin: 0;
}
&#13;
<div id="nav">
    <h1>A website</h1>
    <div class="nav-item">
        <p>Item 1</p>
    </div>
    <div class="nav-item">
        <p>Item 2</p>
    </div>
    <div class="nav-item">
        <p>Item 3</p>
    </div>
</div>
&#13;
&#13;
&#13;

JSFiddle Demo

答案 2 :(得分:-1)

或者您也可以简单地删除height:inherit;:)