Disable line breaks using CSS

2019-02-21 10:43发布

问题:

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