如何删除html元素之间的空格(当margin设置为0时) [英] How to remove spaces between html elements (when margin is set to 0)

查看:115
本文介绍了如何删除html元素之间的空格(当margin设置为0时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个< div> 元素,(或者可以是< li> )其style style = margin:0; display:inline-block;。如果< div> 元素之间存在空格,例如:

Let's say that I have two <div> elements, (or can be <li>) which has style attribute = "margin: 0; display: inline-block;". If there is space between <div> elements, like:

<div style="margin: 0; display: inline-block;">first div</div>
<div style="margin: 0; display: inline-block;">second div</div>



(在这种情况下为secon d元素在不同的行中描述,但它们之间仍然存在大约2-3倍的空间。但是,当我将html代码更改为如下所示:


(In this case second element is described in different line), than still there is about 2-3x space between them. But when I change html code to look like this:

<div style="margin: 0; display: inline-block;">first div</div><div style="margin: 0; display: inline-block;">second div</div>





一切都应该是这样的。可能我应该为整个身体设置一些属性?为什么会发生以及如何避免这些空间?



Everything is like it should be. Probably I should set up some attributes for the whole body? Why does it happen and how to avoid those spaces?

推荐答案

Quote:

为什么会发生?



您的浏览器将换行符视为空格:不是换行符,而是空格。

一个简单的例子来证明这一点:


Your browser treats the line break as whitespace: not as a line break, but as a space.
A simple example to prove this:

a
b



以上代码返回 ab ,代码如下:


The above code returns a b in the browser, however, if you remove the line break, then the code is this:

ab



以上代码在浏览器中返回 ab




And the above code returns ab in the browser.

引用:

如何避免这些空格?



为每个样式属性添加 float:left;


Add float: left; to every style attribute:

<div style="margin: 0; display: inline-block; float: left;">first div</div>
<div style="margin: 0; display: inline-block; float: left;">second div</div>





注意:我建议创建一个CSS类,而不是使用样式属性。

< head> 标记中,添加此< style> 标签:



Note: I suggest to create a CSS class instead of using the style attribute.
In your <head> tag, add this <style> tag:

<!-- in your head-tag -->
<style type="text/css"> 
  div.nospaces {
      margin: 0;
      display: inline-block;
      float: left;
  }
</style>



现在创建时你的 div ,使用 class =nospaces而不是 style =...


And now when creating your div, use class="nospaces" instead of style="...":

<div class="nospaces">first div</div>
<div class="nospaces">second div</div>


这篇关于如何删除html元素之间的空格(当margin设置为0时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆