CSS - divide inline-block span elements with ::bef

2019-04-12 22:21发布

I want to list bits of info divided by pipes, which is easy. But I would like the bits of info to wrap onto multiple lines if the width of the device is slim. I could use a table, but it would take up precious space..

Code: http://jsfiddle.net/Z4NeK/4/

CSS:

span.course-item-details { 
  white-space: pre;
  display: inline-block;
}

p.course-item-meta span~span::before { 
  content: "| ";
}

The text within each span does not wrap, as desired. The spans wrap correctly when the screen is slim. All good!

BUT.. The start of each subsequent line has a divider on it, when the dividers should only be shown between each span.

The | divider is shown only before each span that is preceded by another span, but that's the best I can do. I cannot find a way to select the first element on a line, no matter how many lines the items end up being wrapped to.

I hope that makes sense! Check out the jsfiddle to see the code in action.

I'd really appreciate your input. Any ideas? Is this possible?

Many thanks,

~Rik

标签: html css wrap
2条回答
够拽才男人
2楼-- · 2019-04-12 23:12

You may turn it backwards, using ::after, so this stand alone pipe stands only a the end of the lines except for the last one: TEST

span.course-item-details { 
   white-space: pre;
   display: inline-block;
}

p.course-item-meta span::after { 
   content: "| ";
}
p.course-item-meta span:last-of-type::after { 
   content: "";
}

For the question part about how to select start or end of a line, CSS has no options to do this.

查看更多
Bombasti
3楼-- · 2019-04-12 23:18

You can use a negative margin-left combined with overflow: hidden in an extra wrapper. Then use text-indent to cancel the margin on the first line.

It's best to use a separator that you know the exact width of (e.g. padding+border) rather than text, which will have variable width. This way you can subtract the exact width of the separator via a negative margin.

(Also note the use of font-size: 0 to cancel out the whitespace between inline-block items.)

http://jsfiddle.net/Z4NeK/6/

HTML:

<div class="outer">
    <div class="inner">
        <span class="item">Item one</span>
        <span class="item">Item two</span>
        <span class="item">Item three</span>
        <span class="item">Item four</span>
        <span class="item">Item five</span>
    </div>
</div>

CSS:

.outer {
    text-indent: 5px;
    overflow: hidden;
}

.inner {
    margin-left: -5px;
    font-size: 0;
}

.item {
    text-indent: 0;
    font-size: 1rem;
    padding-left: 4px;
    padding-right: 4px;
    border-left: 1px solid #000;
    display: inline-block;
    white-space: nowrap;
}

.item:first-child {
    padding-left: 0;
    border-left: none;
}

.item:last-child {
    padding-right: 0;
}
查看更多
登录 后发表回答