nine: quick digression for a bear customization. Subtitle: read the $%^#ing manual?
Reading standards is how I relax
I wanted to fix a little thing that's been bugging me in my Bear theme β the lack of customization in the {{ previous_post }} and {{ next_post }} templates. Visually, they only present the linked "previous" or "next" text.
However, in my screen reader testing, VoiceOver was reading the title of the post it would be linking to. That meant the title was somewhere in the code.
Sure enough:
<p>
<a class="previous-post" href="/{link to your last post}" title="{title of your last post}">Previous</a>
<a class="next-post" href="/{link to your next post}" title="{title of your next post}">Next</a>
</p>
If it's there in the HTML, you can use it. I was pretty sure I could pull it off with JavaScript, but my first move whenever I hit a "does X exist" question in CSS (or HTML [or any other standards spec]) is to go straight to the W3C's module documentation. Turns out there's a whole category of CSS functions built for reaching into other parts of the page while it's being styled, before it ever reaches the user: Miscellaneous Value Substituting Functions.
And in that section is this function: attr().
That function can represent a named attribute on an element on your page. So if something in your page is reliably structured, CSS can reach in and grab that specific something. CSS is really good at letting you grab specific parts of a page to manipulate.
So here's how you do it
The browser doesn't apply your stylesheet to raw text. It parses all the HTML first and builds a structured model of the page (the DOM), attributes and all. Only once that model exists does the CSS engine start walking through your rules, matching selectors against parts of the DOM. So by the time attr() runs, the title attribute is already sitting there on the link, waiting to be read.
To grab a named attribute β like a title on a hyperlink β here's what you need to do in your CSS:
- Identify the element that has the thing you want to grab
- Point
attr()at that attribute - Use it somewhere you want it to show up
To select the prev/next links, you can use the classes Bear already supplies: .previous-post, .next-post.
So attr(title) pulls the title attribute off whatever link the selector is currently pointed at. You can do the same thing with other attributes by swapping the name β attr(href) will hand you the URL, to do with what you will.
Now that you have it, you can put it to work. CSS has "pseudo" elements that let you inject content before or after an element β ::before and ::after β using the content property. To grab the title off these links and drop it in right after the selected element, this is all you need:
/* pull the title out of the DOM */
a.previous-post::after,
a.next-post::after {
content: attr(title);
}
And from there, style it however you like. See immediately below for what I did with it.
Previous