I am hiding br
tags in my html on mobile, but would like just the last br
tag to function normally. This seems to work unless the element after the last br
is an anchor tag.
I'm using the following code:
p br {
display: none;
}
p br:last-child {
display: block;
}
<p>lorem
<br>loremlorem lorem
<br>
<br>READ ARTICLE IN JOURNAL</p>
<p>lorem
<br>loremlorem lorem
<br>
<br>
<a href="#">READ ARTICLE IN JOURNAL</a>
</p>
https://jsfiddle.net/5j8dtwfd/2/
The css works as expected with the last br
tag having display:block
applied to it.
However, if I wrap the "read article.." text in an anchor the css stops being able to find the last br
.
I'm not sure what's happening here to cause this, is this the expected behaviour?
With last-child
, you're targeting the last sibling, not necessarily the last br
. In this case, the last sibling is the anchor element. Instead, use last-of-type
.
p br {
display: none;
}
p br:last-of-type {
display: block;
}
<p>lorem
<br>loremlorem lorem
<br>
<br>READ ARTICLE IN JOURNAL
</p>
<p>lorem
<br>loremlorem lorem
<br>
<br><a href="#">READ ARTICLE IN JOURNAL</a>
</p>
Note that in your code, the CSS applies display: block
to p br:last-child
.
Since the last child is blockified, shouldn't the anchor break to a new line anyway?
Not in this case, because the rule applies only if br
is the last child.
So, in sort of a circular fashion, your CSS is targeting the last child, but only if it's a br
, and that's not the case, so nothing happens. The actual last child is an anchor element, but there's nothing targeting it in your CSS.
If you remove the br
from the selector in the original code, it will break the anchor to a new line.
p br {
display: none;
}
p :last-child {
display: block;
}
<p>lorem
<br>loremlorem lorem
<br>
<br>READ ARTICLE IN JOURNAL
</p>
<p>lorem
<br>loremlorem lorem
<br>
<br>
<a href="#">READ ARTICLE IN JOURNAL</a>
</p>
:last-child means the last element in a container. Therefore if the br isn't the last child of the container br:last-child wouldn't work (the a tag is the last child)
What you want is br:last-of-type (https://developer.mozilla.org/en-US/docs/Web/CSS/%3Alast-of-type)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With