我正在尝试获取一个名为 touch-container
的 div
来容纳顶部有 3 个 div 的 canvas
。我也在使用 javascript
调整它们的大小。
问题是 3 个 div 中的每一个都有一个 margin
,它占用了 container 中的剩余空间,即使我明确声明 0 margin
。
这是一个 jsFiddle,如果你检查,你可以看到 margin
Jsfiddle
HTML:
<div id = "touch-container">
<div id = "touch-left" class = "touch-control"></div>
<div id = "touch-middle" class = "touch-control"></div>
<div id = "touch-right" class = "touch-control"></div>
<canvas id = "canvas" width = "960" height = "560"></canvas>
</div>
CSS:
body {
margin: 0;
}
#touch-container{
width: 964px;
height: 560px;
display: inline-block;
margin: 0;
}
.touch-control{
position: relative;
margin: 0;
}
#touch-left{
background-color: red;
}
#touch-middle{
background-color: green;
}
#touch-right{
background-color: blue;
}
JS:
var leftTouch = document.getElementById('touch-left');
var upTouch = document.getElementById('touch-middle');
var rightTouch = document.getElementById('touch-right');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var width = (canvas.width > canvas.height ? canvas.width : canvas.height);
var height = (canvas.height > canvas.width ? canvas.width : canvas.height);
leftTouch.style.width = (width/ 4) + 'px';
leftTouch.style.height = height + 'px';
upTouch.style.width = (width/ 2) + 'px';
upTouch.style.height = height + 'px';
rightTouch.style.width = (width/ 4) + 'px';
rightTouch.style.height = height + 'px';
ctx.fillRect(0,0,canvas.width, canvas.height);
我已经给它们上色了,所以它应该是底部上的一个黑色方 block ,然后从左到右,一个红色的,绿色和蓝色方 block 分别占据 25%、50% 25%
的容器,所以你甚至看不到黑色的 Canvas
.
最佳答案
你没有在你的元素(正方形)中添加任何float
,所以正方形不知道它们应该如何定位,你最常使用float:left;
强制方 block 在同一行并且 display:inline-block;
在你的情况下不起作用(它只适用于文本):
CSS:
#touch-container{
width: 964px;
height: 560px;
display: block;/* new update */
margin: 0;
}
#touch-left{
background-color: red;
float:left;/* new update from here to below */
display:block;
}
#touch-middle{
background-color: green;
float:left;/* new update from here to below */
display:block;
}
#touch-right{
background-color: blue;
float:left;/* new update from here to below */
display:block;
}
关于javascript - 当我将 div 和 body 的边距设置为 0 时,div 有边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737528/