You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用display: table-cell时100vh/100vw无法全屏的问题求助

问题:使用display: table-cell实现全屏居中的

我尝试创建一个<noscript>元素,使其全屏显示且文本居中,采用display: table-cell实现。设置height:100vh、width:100vw后,该元素周围出现莫名空白区域,宽度未铺满屏幕,页面还存在可向下滚动的空间。我已尝试将margin、border、padding设为0,但无任何效果。以下是我的代码(<noscript>已替换为<div>以方便调试):

原CSS代码

* {
    position: relative;
    box-sizing: border-box;
    font-family: "Fira Mono", monospace;
}

body {
    background-color: #0000ff;
}

#noscript {
    display: table-cell;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #000000;
    height: 100vh;
    width: 100vw;
    vertical-align: middle;
    text-align: center;
    color: #ffffff;
    font-size: 1em;
    font-weight: bold;
}

原HTML代码

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div id="noscript">javascript is required to run this game!</div>
    </body>
</html>

解决方案

问题根源在于display: table-cell的特性和浏览器默认样式:

  1. table-cell元素必须嵌套在display: table容器内,否则浏览器会自动生成匿名table容器,这个容器自带默认间距,导致元素无法铺满。
  2. body元素默认带有8px左右的margin,会造成外围空白。
  3. width:100vw会包含浏览器滚动条宽度,可能引发横向滚动。

修改后的代码如下:

修改后的CSS代码

* {
    position: relative;
    box-sizing: border-box;
    font-family: "Fira Mono", monospace;
    margin: 0;
    padding: 0;
}

body {
    background-color: #0000ff;
    display: table;
    width: 100vw;
    height: 100vh;
    overflow: hidden; /* 消除滚动条 */
}

#noscript {
    display: table-cell;
    z-index: 1;
    background-color: #000000;
    vertical-align: middle;
    text-align: center;
    color: #ffffff;
    font-size: 1em;
    font-weight: bold;
}

修改后的HTML代码(换回noscript元素)

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <noscript id="noscript">javascript is required to run this game!</noscript>
    </body>
</html>

说明:

  • 给全局选择器*添加margin:0和padding:0,重置所有元素默认内外边距。
  • 将body设置为display: table,并设置宽高为100vw和100vh,用overflow:hidden禁止滚动。
  • 去掉#noscript的width、height、top、left设置,让table-cell自动填充父容器空间,保留垂直居中和水平居中特性。

内容的提问来源于stack exchange,提问作者alexi zb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:05:03