IT TIP

CSS에서 정렬되지 않은 목록을 쉼표로 구분 된 텍스트로 스타일링하는 방법

itqueen 2020. 11. 27. 21:50
반응형

CSS에서 정렬되지 않은 목록을 쉼표로 구분 된 텍스트로 스타일링하는 방법


인라인으로 렌더링되고 목록 항목이 쉼표로 구분되도록 CSS를 사용하여 XHTML에서 정렬되지 않은 목록을 스타일링하는 방법을 찾고 있습니다.

예를 들어, 다음 목록은 다음과 같이 렌더링되어야합니다 apple, orange, banana(목록 끝에 누락 된 쉼표가 있음).

<ul id="taglist">
  <li>apple</li>
  <li>orange</li>
  <li>banana</li>
</ul>

현재 저는이 목록을 스타일링하기 위해 다음 CSS를 사용하고 있습니다.이 목록은 내가 원하는대로 거의 수행하지만 목록을 다음과 같이 렌더링합니다 apple, orange, banana,(바나나 뒤의 쉼표에주의).

#taglist {
  display: inline;
  list-style: none;
}

#taglist li {
  display: inline;
}

#taglist li:after {
  content: ", ";
}

순수한 CSS로이 문제를 해결할 수있는 방법이 있습니까?


후행 쉼표를 제거하려면 :last-child다음과 같이 의사 클래스를 사용하십시오 .

#taglist li:last-child:after {
    content: "";
}

하나 의 규칙 교체

#taglist li:after {
    content: ", ";
}

단지 또 다른 하나

#taglist li + li:before {
    content: ", ";
}

장점 :

  • 하나의 규칙이 모든 작업을 수행 합니다.
  • 이전 규칙 취소 규칙이 없습니다.
  • IE8 지원

그것은 당신이 의사 선택을 사용할 수 있습니다 CSS3와 함께 쉽게 last-child하고 not한 번에 :

ul#taglist li:not(:last-child):after {
    content: ", ";
}

여기에서 결과 확인 https://jsfiddle.net/vpd4bnq1/


브라우저 구현에 따라 다르지만 작동합니다. 에 의존 first-child하지만 사용을 제한 할 수 있지만 본질적으로 쉼표 공간 ", "을 목록 항목 뒤에 두지 않고 넣습니다 . padding/ margins가 이것에 어떻게 영향을 미칠지 모르겠지만`display : inline; 여백과 패딩을 0으로 설정하면 괜찮습니다.

#taglist li:before {content: ", ";}
#taglist first-child {content: ""; } /* empty string */

편집 됨 : Jakob의 의견에 제공된 수정 사항 에 응답합니다.

다음 작품 (데모 페이지는 여기 : http://davidrhysthomas.co.uk/so/liststyles.html :

#taglist    {width: 50%;
        margin: 1em auto;
        padding: 0;
        }

li      {display: inline;
        margin: 0;
        padding: 0;
        }

li:before   {content: ", ";
        }

#taglist li:first-child:before
        {content: "";
        }

Although the commas are strangely floating-in-the-middle-of-nowhere, and, honestly, I prefer the accepted answer anyway. But just so's I wasn't leaving a horribly broken answer lying around, I thought I should fix it.

Thanks, Jakob.


This is the way that the guys at A List Apart recommend in their article “Taming Lists":

#taglist ul li:after {
    content: ",";
}

#taglist ul li.last:after {
    content: "";
}

This requires having the last item in your list tagged with a class attribute value of “last”:

<ul id="taglist">
  <li>apple</li>
  <li>orange</li>
  <li class="last">banana</li>
</ul>

There is no pure css way to do it that's cross-browser compatible ( thanks to Microsoft ). I suggest you just do it with server-side logic.

You can probably get close with using a last class on the last li and using background images for all lis but the last, but you will not be able to do :last-child and content: in IEs.

참고URL : https://stackoverflow.com/questions/1517220/how-to-style-unordered-lists-in-css-as-comma-separated-text

반응형