Issue
Problem
Styles are not being updated when the last-child changes due to extra elements being added dynamically with JavaScript.
Example
Click "Add more blocks" in the snippet below. When the new blocks are added the fourth .block element ("Test block 4") will not have a bottom red border even though it is no longer the last element in #container.
$("#addMore").one("click", function() {
$("#container").append($("#container").html());
$(this).remove();
});
.block {
border-bottom: 1px solid red;
counter-increment: block;
margin: 20px 0;
position: relative;
}
.block:after {
content: " " counter(block);
}
.block:last-child {
border-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="block">Test block</div>
<div class="block">Test block</div>
<div class="block">Test block</div>
<div class="block">Test block</div>
</div>
<div id="addMore">Add more blocks</div>
Expected behaviour
After clicking "Add more blocks" all .block elements should have a bottom red border except the eighth block ("Test block 8").
Browsers effected
Tested and not working in Chrome 55.0.2883.87 m. Expected behavior returned by IE 11.0.9600.18538 and Firefox 50.1.0.
Can this be resolved without:
- Using JavaScript (i.e. dynamically adding a class which removes the red border from the last element)?
- Restructuring the CSS to not use
last-child(i.e. usingfirst-childandborder-topinstead)?
Solution
For what it's worth, as a workaround you could replace the last-child pseudo class with nth-last-child(1) which does exactly the same thing as last-child, but is unaffected by the bug.
$("#addMore").one("click", function() {
$("#container").append($("#container").html());
$(this).remove();
});
.block {
border-bottom: 1px solid red;
counter-increment: block;
margin: 20px 0;
position: relative;
}
.block:after {
content: " " counter(block);
}
.block:nth-last-child(1) {
border-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div class="block">Test block</div>
<div class="block">Test block</div>
<div class="block">Test block</div>
<div class="block">Test block</div>
</div>
<div id="addMore">Add more blocks</div>
Answered By - Danield
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.