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!
If you want to limit the text length to one line, you can clip the line, display an ellipsis or a custom string. All these can be done with the CSS text-overflow property, which determines how the overflowed content must be signalled to the user.
There are several ways to prevent line breaks in content. Using is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.
<nobr>: The Non-Breaking Text element Be aware that this feature may cease to work at any time. The <nobr> HTML element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With