I'm trying to make a background
with last-child
and I don't really understand why it doesn't apply the style I want. I want the last div
one that contains the child class to have the background
, how can I do it? SOMETHING IS WRONG.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.hijo {
display: block;
width: 100px;
height: 100px;
border:1px solid red;
}
.hijo:last-child {
background: #ff0000;
}
.hermano {
display: block;
width: 100px;
height: 100px;
border: 1px solid green;
}
</style>
</head>
<body>
<div style="width: 100%; height: 100vh; border: 1px solid #000;">
<div class="hijo">
<p>ESTO ES UN TEST</p>
</div>
<div class="hijo">
<p>ESTO ES UN TEST</p>
</div>
<div class="hijo">
<p>ESTO ES UN TEST</p>
</div>
<div class="hijo">
<p>ESTO ES UN TEST</p>
</div>
<div class="hijo">
<p>ESTO ES UN TEST</p>
</div>
<div class="hermano"></div>
</div>
</body>
</html>
This happens because you are applying
css
to elements with class.hijo
that they arelast-child
.This check is done inside a parent container which in this case is a DIV
The element that meets the characteristic
last-child
in your case isIn short, there is no such thing
div
as a classhijo
that is the last childlast-child
of a container.If you remove the last one
div
with classhermano
you will see that now there is an element with classhijo
that islast-child
and it will be appliedcss
correctlyEDIT:
If you want to always keep that structure and preserve the element
div
with classhermano
, you just have to create a rule for elements with classhijo
that are the penultimate element .As you have already been told, the style only applies to the .child element that is the last element of its parent, so if you want it to be as I think I am understanding, you should simply add a 'div' without styles between the elements of the class son.
When you give this instruction:
Are you saying:
"To the element
.hijo
that is the last child of its parent element, I apply this style..." .The problem in your HTML code is that the last child of the parent element, in this case the element
div
, is not the last element.hijo
, but the element.hermano
.The solution? It simply removes the element
.hermano
from the HTML code.To achieve that you need to change the selector, you cannot use
last-child
it because there is no element with a child class that is the last child of the parent container, you must use:nth-child(n)
and select the required element by means of its index, which in this case would be 5.Example: