为什么CSS高度100%不适用于普通div? [英] Why css height 100% is not applying for normal div?

查看:60
本文介绍了为什么CSS高度100%不适用于普通div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的简单代码

<!DOCTYPE html>
<html>
    <head>
        <style>
            div{height:100%;width:100%;background:red;position:relative;}
        </style>
    </head>
    <body>
        <div></div>
    </body>
</html>

CSS高度100%不适用于DIV.

CSS height 100% is not applying for DIV.

我知道一些其他的CSS代码来获取此代码.但是为什么这段代码不起作用.在没有任何脚本的情况下如何在高度100%和宽度100%上工作.

I know some other css code to obtain this. But why this code is not working. how to work on height 100% and width 100% without any script.

推荐答案

要使正常工作,您还需要设置父元素的高度.

For % to work you need to set height for parent element as well.

设置 html,正文{高度:100%}

从文档中-

相对于高度计算包含块.如果包含块的高度不是明确指定后,该值将自动计算.身高百分比根元素上的(例如)相对于初始元素包含块(其尺寸等于视口).

The is calculated with respect to the height of the containing block. If the height of the containing block is not specified explicitly, the value computes to auto. A percentage height on the root element (e.g. ) is relative to the initial containing block (whose dimensions are equal to the dimensions of the viewport).

有关更多信息,请访问- MDN百分比文档

Check more on this at - MDN Percent Doc

因此,就您而言,您可以这样做-

So in your case, you can do like this -

<!DOCTYPE html>
<html>
    <head>
        <style>
            html,body{height:100%;}
        div{height:100%;width:100%;background:red;position:relative;}
        </style>
    </head>
    <body>
        <div></div>
    </body>
</html>

这篇关于为什么CSS高度100%不适用于普通div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆