Add space between HTML elements only using CSS

一曲冷凌霜 提交于 2019-11-29 19:30:07
thirtydot

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

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.

Ben

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

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.

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/

You can write like this:

span{
 margin-left:10px;
}
span:first-child{
 margin-left:0;
}
span:not(:last-child) {
    margin-right: 10px;
}
Moe Sweet

<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.

You should wrap your elements inside a container, then use new CSS3 features like css grid, free course, and then use grid-gap:value that was created for your specific problem

span{
  border:1px solid red;
}
.inRow{
  display:grid;
  grid-template-columns:repeat(auto-fill,auto);
  grid-gap:10px /*This add space between elements, only works on grid items*/
}
.inColumn{
  display:grid;
  grid-template-rows:repeat(auto-fill,auto);
  grid-gap:15px;
}
<div class="inrow">
  <span>1</span>
  <span>2</span>
  <span>3</span>
</div>
<div class="inColumn">
  <span>4</span>
  <span>5</span>
  <span>6</span>
</div>
span.middle {
    margin: 0 10px 0 10px; /*top right bottom left */
}

<span>text</span> <span class="middle">text</span> <span>text</span>
jalooc

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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!