Learning
Learning

Reputation: 20001

how to change css of n number of div element using jquery

I need to show 16 div in a format of 4x4 in case screen width is greater than 960px; and show 3x4 divs if screen width is 746px and 2x6 in can width is 480px

and 1x16 if screen width is 32px;

i need to write a jquery where let us say if screen size is greater than 960px then i need to remove border from last 4 divs.

I am not sure how to make it work example on fiddle http://jsfiddle.net/krGQc/42/

<div class="tdiv">1</div>
<div class="tdiv">2</div>
<div class="tdiv">3</div>
<div class="tdiv">4</div>
<div class="tdiv">5</div>
<div class="tdiv">6</div>
<div class="tdiv">7</div>
<div class="tdiv">8</div>
<div class="tdiv">9</div>
<div class="tdiv">10</div>

Upvotes: 0

Views: 166

Answers (4)

kei
kei

Reputation: 20491

Using CSS media query

@media (min-width: 32px) and (max-width: 479px) { /* 1x16 */
    .tdiv {
        clear:left;
    }
}
@media (min-width: 480px) and (max-width: 745px) { /* 2x6 */
    .tdiv:nth-child(2n+1) {
        clear:left;
    }
    .tdiv:nth-child(n+13) {
        display:none;
    }
}
@media (min-width: 746px) and (max-width: 959px) { /* 3x4 */
    .tdiv:nth-child(3n+1) {
        clear:left;
    }
    .tdiv:nth-child(n+13) {
        display:none;
    }
}
@media (min-width: 960px) { /* 4x4 */
    .tdiv:nth-child(4n+1) {
        clear:left;
    }
}

DEMO

Upvotes: 1

adeneo
adeneo

Reputation: 318222

You can use gt() with a negative index to count backwards from the last element.

if (window.screen.width > 960) { // you asked for "screen"
    $('.tdiv:gt(-5)').css('border','none');
}

FIDDLE

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

using nth-last-child in css:

.tdiv:nth-last-child(-n+4)  {
    border:none;
}

Fiddle

Upvotes: 1

Callidior
Callidior

Reputation: 2904

Use media queries in your CSS stylesheet:

.tdiv {
    /* Styling for width >= 960px */
}

@media all and (max-width: 746px) {

    .tdiv {
        /* Styling for width <= 746px */
    }

}

@media all and (max-width: 480px) {

    .tdiv {
        /* Styling for width <= 480px */
    }

}

You can use the pseudo-class selectors :nth-child() and :nth-last-child() to hide the last n elements or remove the borders from it.

Upvotes: 1

Related Questions