Add space between HTML elements only using CSS
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.
Solution 1:
A good way to do it is this:
span + span {
margin-left: 10px;
}
Every span
preceded by a span
(so, every span
except the first) will have margin-left: 10px
.
Here's a more detailed answer to a similar question: Separators between elements without hacks
Solution 2:
Just use margin or padding.
In your specific case, you could use margin:0 10px
only on the 2nd <span>
.
UPDATE
Here's a nice CSS3 solution (jsFiddle):
span {
margin: 0 10px;
}
span:first-of-type {
margin-left: 0;
}
span:last-of-type {
margin-right: 0;
}
Advanced element selection using selectors like :nth-child()
, :last-child
, :first-of-type
, etc. is supported since Internet Explorer 9.
Solution 3:
add these rules to the parent container:
display: grid
grid-auto-flow: column
grid-column-gap: 10px
Good reference: https://cssreference.io/
Browser compatibility: https://gridbyexample.com/browsers/
Solution 4:
You can style elements with excluding first one, just in one line of code:
span ~ span {
padding-left: 10px;
}
No need to change any classes.
Solution 5:
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