在换行后删除inline-block元素的边距 [英] Removing margin on inline-block element after wrapping lines
问题描述
我希望没有JavaScript可以做到这一点。我有两个元素显示与inline-block。它们的宽度和高度都是200像素,因此它们都显示在同一行上,除非浏览器的大小非常小(或使用移动浏览器)。我想要两个元素之间有一个50像素的空间,所以在第二个元素,我添加了margin-left:50px,这很好。当浏览器调整为两个元素都不能放在同一行的大小时,第二个元素将换行到下一行,这是我想要的。问题是第二个元素仍然有50px左边距,因此元素不会出现居中。我可以添加JavaScript来检测容器高度变化(即元素是否包装到下一行)并删除左边距,但是有没有JavaScript可以实现这一点?
I'm hoping there's a way to do this without JavaScript. I have two elements displayed with inline-block. They are both 200 pixels in width and height, so they both appear on the same line unless the browser is sized very small (or with mobile browsers). I want there to be a 50px space between the two elements, so on the second element I added "margin-left: 50px", which works fine. When the browser is resized to a size where both elements cannot fit on the same line, the second element wraps to the next line, which is what I want it to do. The problem is that the second element still has the 50px left margin, so the elements don't appear centered. I could add JavaScript to detect when the container height changes (i.e. the element wrapped to the next line) and remove the left margin, but is there a way to accomplish this without JavaScript?
这是我的代码,简化:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="wrapper" style="text-align: center;">
<div id="elem1" style="display: inline-block; background-color: #f00; width: 200px; height: 200px;"></div>
<div id="elem2" style="display: inline-block; background-color: #00f; width: 200px; height: 200px; margin-left: 50px;"></div>
</div>
</body>
</html>
小提琴: http: //jsfiddle.net/YRshx/
推荐答案
根据bastianonm的解决方案,尝试:
Based on bastianonm's solution, try this:
<div id="wrapper" style="text-align: center; margin:0 -25px;">
<div id="elem1" style="display: inline-block; background-color: #f00; width: 200px; height: 200px; margin:0 25px;"></div>
<div id="elem2" style="display: inline-block; background-color: #00f; width: 200px; height: 200px; margin:0 25px;"></div>
</div>
这篇关于在换行后删除inline-block元素的边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!