Add space between HTML elements only using CSS

2019-01-30 04:39发布

I have several same HTML elements going one after another:

<span>1</span>
<span>2</span>
<span>3</span>

I'm looking for the best way of adding space BETWEEN the elements using CSS only

[no space]  [1]  [space 10px]  [2]  [space 10px]  [3]  [no space]

Additionally:

  • Please write down browser compatibility of your receipts

UPDATE

It looks like I was unclear. I don't want to use ANY ADDITIONAL HTML MARKUP like

<span></span>  <span></span>  <span class="last_span"></span>

I don't want to use tables

I want the first and last span to be targeted automatically by CSS

I don't want to use javascript

Optional requirement: last span can be NOT LAST CHILD of the parent tag, but it will be the LAST SPAN of the parent tag. Spans do not have any other tags between them.

10条回答
可以哭但决不认输i
2楼-- · 2019-01-30 05:01
span:not(:last-child) {
    margin-right: 10px;
}
查看更多
成全新的幸福
3楼-- · 2019-01-30 05:03

You can write like this:

span{
 margin-left:10px;
}
span:first-child{
 margin-left:0;
}
查看更多
老娘就宠你
4楼-- · 2019-01-30 05:07

That's so easy.

You can style elements with excluding first one, just in one line of code:

span ~ span {
padding-left: 10px;
}

and done, with no class manipulating.

查看更多
贼婆χ
5楼-- · 2019-01-30 05:09

You can take advantage of the fact that span is an inline element

span{
     word-spacing:10px;
}

However, this solution will break if you have more than one word of text in your span

查看更多
迷人小祖宗
6楼-- · 2019-01-30 05:10

<span> is an inline element so you cant make spacing on them without making it block level. Try this

Horizontal

span{
    margin-right: 10px;
    float: left;
}

Vertical

span{
    margin-bottom: 10px;
}

Compatible with all browsers.

查看更多
beautiful°
7楼-- · 2019-01-30 05:14

Or, instead of setting margin and than overriding it, you can just set it properly right away with the following combo:

span:not(:first-of-type) {
    margin-left:  5px;
}

span:not(:last-of-type) {
    margin-right: 5px;
}
查看更多
登录 后发表回答