javascript - 当我将 div 和 body 的边距设置为 0 时,div 有边距

标签 javascript html css

我正在尝试获取一个名为 touch-containerdiv 来容纳顶部有 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; 在你的情况下不起作用(它只适用于文本):

Jsfiddle

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/

相关文章:

javascript - 如何使用 Jquery 循环变量

javascript - 如何设置具有多个条件的if语句,在if语句中使用有效条件的变量?

javascript - 从输入类型密码到范围获取尾随空格?

html - 重复线性渐变突然在折痕下切割

javascript - 没有复制权限的 HTML 选择

Javascript 验证 : compare string in dropdown list with other column in a table

javascript - 在 OpenUI5 中强制清除缓存

javascript - 将按钮附加到网站时,如何停止 .each 循环的值相同?

javascript - 使用 js/jquery 进行动态输入

css - 帮助控制 div 中的链接