11

我在 div 元素中有一个画布元素。画布大小可以改变,我希望它垂直居中。我正在使用这种 CSS 方法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Vertical Centering</title>

    <style>
        html,
        body{
            height:100%;
            width:100%;
            margin:0;
            padding:0;
        }
        #container{
            width:100%;
            height:100%;
            text-align:center;
            font-size:0;

            background:#aae;
        }
        #container:before{
            content:'';
            display:inline-block;
            height:100%;
            vertical-align:middle;
        }

        canvas{
            width:400px;
            height:300px;

            display:inline-block;
            vertical-align:middle;

            background:#fff;
        }
    </style>
</head>
<body>

    <div id="container">
        <canvas></canvas>
    </div>

</body>
</html>

你可以看到它在这个小提琴上工作:http: //jsfiddle.net/8FPxN/

这段代码对我很有用,直到浏览器在画布宽度下调整大小。选择器定义的虚拟元素:before站在第一行,画布落到第二行。我试图让它们保持不变,避免换行,并在需要时显示滚动条。将overflow:auto规则添加到容器中会显示滚动条,但线条会不断中断。

画布大小可以更改,因此该top:50%; margin-top:- ($canvas_height / 2);方法不适合这种情况。嗯,可以,但我不喜欢控制margin-top使用 JavaScript。只是 CSS 会很棒。

有任何想法吗?谢谢!

4

2 回答 2

24

似乎(从有限的测试)添加white-space: nowrap;工作:

#container{
    width:100%;
    height:100%;
    text-align:center;
    font-size:0;

    background:#aae;
    white-space: nowrap;
}

更新了 JS Fiddle 演示

于 2013-05-05T10:16:31.883 回答
2

添加 white-space:nowrap 应该可以解决问题。http://jsfiddle.net/David_Knowles/aEvG5/

#container{
    width:100%;
    height:100%;
    text-align:center;
    font-size:0;
    white-space:nowrap;
}

编辑:正确的小提琴

于 2013-05-05T10:18:10.973 回答