【问题标题】:Height works in pixels, not in percentages高度以像素为单位,而不是百分比
【发布时间】:2015-03-22 02:21:22
【问题描述】:

我正在尝试使用以下 html 设置创建一个简单的菜单:

<div class="container">
    <div class="container-cell">
        <a href="play.html">
            <div class="menu-option no-margintop">
                <div class="play-icon">
                    <span class="helper"></span><img src="./img/icon_1.png"/>
                </div>
                <div class="menu-text"><span>Play</span></div>
            </div>
        </a>
        <a href="index.html">
            <div class="menu-option">
                <div class="play-icon">
                    <span class="helper"></span><img src="./img/icon_3.png"/>
                </div>
                <div class="menu-text"><span>Highscore</span></div>
            </div>
        </a>
        <a href="index.html">
            <div class="menu-option">
                <div class="play-icon">
                    <span class="helper"></span><img src="./img/icon_2.png"/>
                </div>
                <div class="menu-text"><span>FAQ</span></div>
            </div>
        </a>
    </div>
</div>

在创建这个的过程中,我从硬像素切换到百分比。虽然设置高度的像素版本有效,但它似乎不适用于百分比。一个特定类的高度,menu-option,似乎没有被浏览器接收到。

我已经搜索了一段时间,我遇到的唯一解决方案是为 body 和 html (100%) 设置高度。我还为任何容器元素设置了高度。

请参阅下面的 css:

html, body{
    height:100%;
}

.container {
    display:table;
    width:100%;
    height:70%;
}

.container-cell {
    display:table-cell;
    vertical-align: middle;
    height:100%;
}

.menu-option{
    width:90%;
    margin-left:5%;
    border-radius:10px;
    background-color:rgba(17,23,28,0.2);
    height:6.94%;
    margin-top:5%;
    font-size:150%;
}

为什么浏览器没有使用百分比高度,如何让它使用百分比高度?

【问题讨论】:

    标签: html css


    【解决方案1】:

    display: inline-block; 添加到您的菜单选项类以使高度属性起作用。像这样的:

    .menu-option{
        display: inline-block;
        width:90%;
        margin-left:5%;
        border-radius:10px;
        background-color:rgba(17,23,28,0.2);
        height:6.94%;
        margin-top:5%;
        font-size:150%;
    }
    

    这是上面的一个 jsfiddle:https://jsfiddle.net/AndrewL32/e0d8my79/17/

    【讨论】:

    • 行得通!谢谢 ;) 不过我很好奇,为什么需要这样做?
    • inline-block 元素 类似于内联元素,但它们可以具有特定的宽度和高度。检查此链接:stackoverflow.com/questions/9189810/… Ticked 答案对不同类型的显示元素进行了非常描述性的解释:)
    • 因为内联元素不能设置高度。只有当它基于设置了高度的父元素时,百分比才有效。
    • 这就解释了。谢谢大家的帮助!
    猜你喜欢
    • 2014-06-07
    • 2015-04-02
    • 2014-03-05
    • 2013-03-05
    • 2013-06-22
    • 2015-06-12
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多