CSS :before and :first-child combined

前端 未结 2 842
野性不改
野性不改 2021-02-11 12:16

I\'m using the following code to add separators between my menu items:

#navigation_center li:before {

    content: \"| \";
    color: #fff;

}

2条回答
  •  感情败类
    2021-02-11 12:42

    Although hradac's answer should do the trick i thought it would be best to run through some possible permutations to help newcommers.

    .works:first-child:before
    {
    	color: green;
    	content: 'working ';
    }
    .works:not(:first-child):after
    {
    	color: green;
    	content: ' is working';
    }
    
    
    .broken:before:first-child
    {
    	color: red;
    	content: 'this will never show up';
    }
    .broken:after:not(:first-child)
    {
    	color: red;
    	content: 'and this will not show up either';
    }
    works:
    
    something
    something
    something

    broken:
    something
    something
    something

    Let's take this apart:

    • Three div.works are inside a div
    • Three div.broken are also inside a div
    • The first rule of CSS adds a green text "working " before. It does so by selecting the first-child and then selecting the empty space right before it.
    • The second rule adds " is working" after each block that comes after first, by analogy it first selects each block that doesn't fall under the first-child definition, and then selects the empty space before them.
    • The following two rules, will not find a block to attack themselves to. The :before:first-child attempts to select an empty space, but then tests if it is a first-child and it is not (since technically it's not yet in the DOM tree), the similar problem is with :not(:first-child).

提交回复
热议问题