clear:both 使margin-top失效

上面3个都是float:left

下面的是 clear:both. 为什么无论怎么改margin-top始终都是紧贴的

图片说明

 <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>浮动去空格</title>
<style>
button { margin: 0; }
p { clear: both; }
</style>
</head>

<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<p><input type="button" id="trigger" value="点击按钮浮动"></p>
<script>
var trigger = document.getElementById("trigger"),
    buttons = document.getElementsByTagName("button");

var length = buttons.length;

if (trigger && length > 0) {
    trigger.onclick = function() {
        for (var index = 0; index < length; index += 1) {
            buttons[index].style["cssFloat" in trigger.style? "cssFloat": "styleFloat"] = "left";
        }
    };
}   
</script>
</body>
</html>

解决方案:
把所有button元素用

包起来,设置id
在css里给这个div设置属性:overflow:hidden
即可解决。

button用 div 包起来,这个评论区把 div自动搞成区域了

p、span都是行内元素,只有margin-left和margin-right才有效果。

要想margin-top生效就要把p转给块级元素才行, display: block;

上边的三个元素浮动了 下面的元素用margin-top就会紧贴上边的元素 换成padding-top

改css 就额可以 padding-top 完整代码如下
<!doctype html>



浮动去空格 button { margin: 0; } p { clear:both; padding-top:20px; }

按钮1
按钮2
按钮3
按钮4

var trigger = document.getElementById("trigger"), buttons = document.getElementsByTagName("button"); var length = buttons.length; if (trigger && length > 0) { trigger.onclick = function() { for (var index = 0; index < length; index += 1) { buttons[index].style["cssFloat" in trigger.style? "cssFloat": "styleFloat"] = "left"; } }; }


我认为,你用个div吧按钮包起来

按钮1 按钮2 按钮3 按钮4

你在试试

按钮1
按钮2
按钮3</防乱吗button>
按钮4

《div》按钮1 按钮2 按钮3 按钮4《/div》