LoginSignup
5
7

More than 5 years have passed since last update.

スラッシュで項目を分けたリストの表示をCSS ::before で

Last updated at Posted at 2015-08-16

ブログから転載します。
スラッシュで項目を分けたリストの表示をCSS ::before で

お題

支店: ニューヨーク / 大阪 / ホーチミン市 / プノンペン

こういうやつ、最後のスラッシュがないのがポイント。どうするか、結構めんとくさい。

1. Rubyの場合、下のような感じ

ruby
支店: 
<%= @branches.collect{|branch| branch.name }.join(' / ') %>

わりとスマート。問題なし

2. PHPの場合、下のような感じ

php
支店: 
<?php foreach($branches as $index => $branch)
{ if ($index != 0) echo " / "; echo $branch->name; } ?>

なんか違うかも。

3. Twigの場合、下のような感じ

例1)

twig
支店: {% なんか長くてややこしいコード %}

例2)

twig
支店: {% $branches|list_names_with_seperater(' / ') %}

…..考えるのもいや。

4. 解決策 by CSS

HTMLは普通に羅列するだけ。で囲むのがポイント

html
支店: 
<span class="inline-item">ニューヨーク</span>
<span class="inline-item">大阪</span>
<span class="inline-item">ホーチミン市</span>
<span class="inline-item">プノンペン</span>

::before 擬似要素で / を入れていく、:first-child は表示しない

css
.inline-item::before {
  content: "/";
  margin-left: .5em;  
  margin-right: .5em;  
}
.inline-item:first-child::before {
  content: none;
}

追記:もっとスマートな方法 by @ShibuyaKosuke さん

css
.inline-item + .inline-item::before {
  content: "/";
  margin-left: .5em;  
  margin-right: .5em;  
}

なんか長年の問題が解決して嬉しい。スッキリ。

参考: プログラム組んだら負け!実はHTML/CSSだけでできること2015夏

5
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7