I\'m trying to \"automatically\" add a horizontal-rule after each article in my page. Is there a way of doing this using the :after selector? I\'m hoping to be able to style it
This is impossible with pure CSS, but you could use a border and margins to look like a hr
:
article {
margin: 3px 0px;
border-bottom: 1px solid black;
}
Or you could use JavaScript:
var articles = document.getElementsByTagName('article')
for (var i = 0; i < articles.length; i ++) {
articles[i].parentNode.insertBefore(document.createElement('hr'), articles[i].nextSibling)
}
Or easier in jQuery:
$('article').after('<hr/>')
No you cannot with pure CSS/HTML. You would need some sort of scripting such as Javascript to handle the logic.
Using JQuery:
$(document).ready(function() {
$("article").after("<hr>");
});
CSS only solution
article {
position: relative;
}
article:after {
content: '';
position: absolute;
width: 100%;
height: 1px; // suit your need
background: black; // suit your need
top: 100%;
left: 0;
}
Try this ..
yourclass:before {
content: "";
border-left: 2px solid green;
height: 28px;
margin-right: 15px;
}
I know this is an older question, but considering there aren't yet any correct CSS-only answers (although Bobby was close), I'll add my two cents.
You cannot use CSS to add HTML tags to a page. However, there is a CSS-only solution to achieve the same visual effect.
You can use the ::after
pseudo-element to do this. This creates an element after the specified element, in this case the article
.
Using content: ''
gives an empty element, which we then style to fit the whole width of the screen (width:100vw
), with a height
of our choice (in this case only 1px
) and we give it a background-color
in order to make it visible as a line. Using position:absolute
and left:0
ensures the line will always stick to the left side of the screen, and because it is as wide as the screen, it will always span the entire width.
If you don't want the line spanning the entire screen, you can use 100%
instead of 100vw
to make it span accross whatever element you put it inside. (That would be the article
element's parent in this example).
article {
position: relative;
}
article::after {
content: '';
position: absolute;
width: 100vw;
height: 1px;
left: 0;
display: block;
clear: both;
background-color: black;
}