Disable line breaks using CSS

ぃ、小莉子 提交于 2019-12-01 14:19:28

问题


I have a canvas element inside a div element. The canvas size can change, and I want it vertical centered. I'm using this CSS approach:

<!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>

You can see it working on this fiddle: http://jsfiddle.net/8FPxN/

This code works great for me, until the browser resizes under the canvas width. The virtual element defined by the :before selector stands on the first line, and the canvas falls to the second line. I'm trying to keep them sticked, avoiding the line break, and showing scroll bars when needed. Adding the overflow:auto rule to the container shows the scroll bars, but the line keeps breaking.

The canvas size can change, so the top:50%; margin-top:- ($canvas_height / 2); approach is not suitable for this. Well, it can be, but I prefer not to control the margin-top using JavaScript. Just CSS would be great.

Any ideas? Thanks!


回答1:


It seems (from limited testing) that adding white-space: nowrap; works:

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

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

Updated JS Fiddle demo.




回答2:


Adding white-space:nowrap should do the trick. http://jsfiddle.net/David_Knowles/aEvG5/

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

EDIT: correct fiddle



来源:https://stackoverflow.com/questions/16383483/disable-line-breaks-using-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!