clusterBuddy clusterBuddy - 1 year ago 63
CSS Question

CSS nth-child(n) not responding after being appended with jQuery

my

nth-child()
pseudo element isn't working on the elements.


  • It works just fine on JSFiddle with compiled CSS YET NOT with SCSS.

  • On my machine it doesn't work with either CSS nor SCSS.

  • Please also notice that
    .sketchBoxGame
    nth-child() doesn't work at all.

  • Does this have anything to do with jQuery creating and populating the elements without considering pseudo-elements?



What's going on here?

HTML:

<div id="game" class="container-fluid">
<div class="row">
<div class="container-sketch text-center"></div>
</div>
</div>


CSS:

.sketchBoxGame {
width: 100px;
height: 100px;
//background-color: white;
border: 1px solid black;
display: inline-block;
vertical-align: top;
margin: 5px;
&:nth-child(2) {
background-color: #3c763d;
}
}
.sketchBoxIcon{
width: 100px;
height: 100px;
display: inline-block;
vertical-align: top;
margin: 5px;
background-color: #5bc0de;
}


JS:

var main = function () {
iconBoxes();
gameBoxes();
};
//Miki - here you can determine how many boxes you want per height/width
var gameBoxWidth = 3;
var gameBoxHeight = 3;

var iconBoxWidth = 3;
var iconBoxHeight = 1;

var containerSketch = '.container-sketch';
var sketchBoxGame = '.sketchBoxGame';
var sketchBoxIcon = '.sketchBoxIcon';

var gameBoxes = function () {
$('sketchBoxGame').remove();
for (var i = 0; i < gameBoxHeight; i++) {
for (var j = 0; j < gameBoxWidth; j++) {
$(containerSketch).append('<div class="sketchBoxGame"></div>');
}
$(containerSketch).append('<br>');
}
};
var iconBoxes = function () {
for (var i = 0; i < iconBoxHeight; i++) {
for (var j = 0; j < iconBoxWidth; j++) {
$(containerSketch).append('<div class="sketchBoxIcon"></div>');
}
$(containerSketch).append('<br>');
}

};

$(document).ready(main);

Answer Source

Please also notice that .sketchBoxGame nth-child() doesn't work at all.

That's because there is no .sketchBoxGame element that is 2nd child... They are put after 3 .sketchBoxIcon elements. I am guessing that you want to flag the 2nd element of each row, to do so, simply wrap every elements of a row in a container.

var gameBoxes = function () {
    $('sketchBoxGame').remove();
    for (var i = 0; i < gameBoxHeight; i++) {
        var $row = $(containerSketch).append('<div>');
        for (var j = 0; j < gameBoxWidth; j++) {
            $row.append('<div class="sketchBoxGame"></div>');
        }
    }
};

I had forgot, but you can use the (an + b) formula in nth-child like so

.sketchBoxGame:nth-child(4n+2) {
    background-color: #3c763d;
}

This targets every 2nd element of every 4 elements repetitions. (It is 4 because you got three sketchBoxGame + one BR element.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download