Apply CSS styles to elements from 1 + n?

0

I do not plan much and I have found a certain situation.

I have a series of paragraphs inside a div. I would like to apply a CSS style to all the paragraphs from a certain position , for example, from the third paragraph the rest will not appear, that is, the following code:

<div class="prueba">
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
</div>

show only:

lorem ipsum
lorem ipsum
lorem ipsum


Note: The number of paragraphs is indeterminate, so I can not do something like:

p:nth-of-type(4),
p:nth-of-type(5) {
  display: none;
}
    
asked by Orici 18.12.2018 в 00:57
source

2 answers

4

Assuming that your element from which you want to apply something is the fourth, you must use the pseudo selector :nth-of-type sending it a formula.

The formulas are made as follows:

an+b

Where one of the elements goes means:

  • n is our variable, if we do not put anything it will apply to all
  • a is the quantifier of multiples if we put for example 2n will apply it every n that is divisible exactly between 2
  • b is our lag. That is, starting from this number of elements, the rest of the formula begins to be applied.

p:nth-of-type(n+4) {
  /* display: none;*/
   background: red;
}
<div class="prueba">
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
    <p>lorem ipsum</p>
</div>
    
answered by 18.12.2018 / 01:33
source
0

I found a possible solution combining CSS selectors :

.prueba p:nth-of-type(3) ~ p {
    display: none;
}

First I select the element that preceded those who will carry the style, in this case the third paragraph, which will be the last one visible within the div. From this element, he used the selector ~ to select the remaining elements of type paragraph that remain.

    
answered by 18.12.2018 в 01:08