【问题标题】:Disable line breaks using CSS使用 CSS 禁用换行符
【发布时间】:2013-04-29 07:22:51
【问题描述】:

我在 div 元素中有一个 canvas 元素。画布大小可以改变,我希望它垂直居中。我正在使用这种 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); 方法不适合这种情况。嗯,可以,但我不喜欢使用 JavaScript 控制margin-top。只有 CSS 会很棒。

有什么想法吗?谢谢!

【问题讨论】:

    标签: css vertical-alignment line-breaks


    【解决方案1】:

    似乎(通过有限的测试)添加white-space: nowrap; 有效:

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

    Updated JS Fiddle demo.

    【讨论】:

      【解决方案2】:

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

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

      编辑:正确的小提琴

      【讨论】:

      • 谢谢!你的答案是正确的,但你的小提琴不相关。
      猜你喜欢
      • 2018-05-27
      • 2012-06-11
      • 1970-01-01
      • 2016-07-17
      • 1970-01-01
      • 2017-10-15
      • 2011-06-21
      • 2011-04-25
      • 2015-10-22
      相关资源
      最近更新 更多