使用CSS禁用换行符
我在div元素中有一个canvas元素。画布大小可以改变,我想它垂直居中。我使用这种CSS方法:
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>
你可以看到它在这个小提琴上工作:http://jsfiddle.net/8FPxN/
You can see it working on this fiddle: http://jsfiddle.net/8FPxN/
此代码适用于我,直到浏览器在画布宽度下调整大小。由:before
选择器定义的虚拟元素位于第一行,画布落在第二行。我想保持他们粘,避免换行,并在需要时显示滚动条。将 overflow:auto
规则添加到容器中将显示滚动条,但是该行仍在破坏。
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.
大小可以改变,所以 top:50%; margin-top: - ($ canvas_height / 2);
方法不适合这个。好吧,它可以,但我不喜欢使用JavaScript控制 margin-top
。只是CSS将是伟大的。
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.
任何想法?谢谢!