블로그 메뉴

    Tonkatsu
    Developer Lee
    Tonkatsu
    전체 방문자
    오늘
    어제
    • 분류 전체보기 (52)
      • Frontend (7)
        • React (3)
        • JavaScript (3)
        • HTML\CSS (1)
        • etc (0)
      • Backend (0)
        • Python\Django (0)
        • etc (0)
      • CS (32)
        • Algorithm\Coding Test (19)
        • Computer Science (8)
        • devops (5)
        • etc (0)
      • Languages (5)
        • Javascript (5)
        • Python (0)
        • etc (0)
      • 비상다반 (3)
      • 학원 (4)

    인기 글

    태그

    • BFS
    • HTML
    • 프론트엔드
    • DFS
    • 백준
    • fetch
    • 자바스크립트
    • Push
    • 프로그래머스
    • leetcode
    • Git
    • 리트코드
    • 코테
    • merge
    • CS
    • 코딩테스트
    • 네트워크
    • javascript
    • CSS
    • js

    최근 댓글

    최근 글

    티스토리

    hELLO · Designed By 정상우.
    Tonkatsu

    Developer Lee

    css : 인접 형제 결합자 +
    Frontend/HTML\CSS

    css : 인접 형제 결합자 +

    2021. 12. 9. 15:43

    종종 메뉴나 목록을 만들 때, 그 사이 구분선을 넣으면서 어쩔 수 없이 :last-child, :first-child를 쓸 일이 있다.

    아래와 같은 예를 보자.

     

      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
      </ul>

     

        li {
          width: 50px;
          height: 20px;
          display: inline-block;
          background-color: cornflowerblue;
          text-align: center;
          margin: 0 10px;
          position: relative;
        }

     

     

    만약 위 5개의 li 사이에 구분자 '|' 를 넣고 싶다고 해보자.

     

        li {
          width: 50px;
          height: 20px;
          display: inline-block;
          background-color: cornflowerblue;
          text-align: center;
          margin: 0 10px;
          position: relative;
        }
    
        li::after {
          content: "|";
          position: absolute;
          left: -13px;
        }
    
        li:first-child::after {
          content: '';
        }

     

    위 방법이 평범한 방법이다. 

    ::after를 통해 모든 li에 '|'를 삽입한 후에, 첫번째 li는 '|'를 제거하는 방법이다.

    하지만 + 연산자를 이용하면 이런 방법을 사용하지 않고 한번에 처리할 수 있다.

     

        li {
          width: 50px;
          height: 20px;
          display: inline-block;
          background-color: cornflowerblue;
          text-align: center;
          margin: 0 10px;
          position: relative;
        }
    
        li+li::after {
          content: "|";
          position: absolute;
          left: -13px;
        }

     

    위와 같은 결과가 나온다.

    왜 같은 결과가 나오는 것일까?

     

    li + li는 앞에 li가 붙어 있는 li만 선택되기 때문에 1번째 li는 선택되지 않고 (앞에 아무것도 없으므로) 2, 3, 4, 5 번째 li만 선택되는 것이다.

    따라서 li:first-child가 이미 예외처리 되어 있기 때문에 따로 설정하지 않아도 된다.

     

    따라서 여러 요소들 사이에만 margin등을 주고 싶은 경우에도 유용하게 사용되면서 코드가 간결해질 수 있다.

    저작자표시 (새창열림)
      Tonkatsu
      Tonkatsu
      한 번 뿐인 인생 편하게 살고싶지만 그러려면 열심히 살아야 되니까 열심히 살려고 노력은 하지만 편하게 사는 사람

      티스토리툴바