CSS has a lesser-known :target
selector to style an element that matches the element linked in the page hash.
This can be useful to highlight the section the user intended to visit.
<h2 id="introduction">Introduction</h2>
<!-- … -->
<h2 id="how-to-send-a-campaign">How to send a campaign</h2>
<!-- … -->
<h2 id="dealing-with-bounces">Dealing with bounces</h2>
<!-- … -->
When someone is linked to https://www.mailcoach.app/#how-to-send-a-campaign
, the target selector can be used to make the title stand out between the rest of the content.
h2:target {
background-color: yellow;
}
We can also display hidden content with the :target
selector. This can be useful to display flash message when a user is directed to a specific URL.
<p id="subscribed">Thanks for subscribing!</p>
#subscribed {
display: none;
}
#subscribed:target {
display: block;
}
The thank you message is hidden by default, but when a user visits #subscribed
, they’ll see the method.
With the :target
selector, we can set up a Mailcoach subscribe form with a custom success message. On this page, we have a thank you message, already subscribed message, and subscription form.
<p id="subscribed">Thanks for subscribing!</p>
<p id="already-subscribed">You were already subscribed.</p>
<form id="form" method="post" action="https://www.mailcoach.app/subscribe/…">
<input type="email" name="email" placeholder="blake@example.com">
<button type="submit">Subscribe</button>
</form>
By default, we’ll hide the messages.
#subscribed,
#already-subscribed {
display: none;
}
When the new subscriber is redirected to a URL containing one of the targets, we’ll display them.
#subscribed:target,
#already-subscribed:target {
display: block;
}
<form id="form" method="post" action="https://www.mailcoach.app/subscribe/…">
<input type="email" name="email" placeholder="blake@example.com">
<input type="hidden" name="redirect_after_subscribed" value="https://mysite.com/#subscribed">
<input type="hidden" name="redirect_after_already_subscribed" value="https://mysite.com/#already-subscribed" />
<button type="submit">Subscribe</button>
</form>
Mailcoach supports a few hidden fields to alter the configuration of the subscribe form. We can set the redirect URLs with redirect_after_subscribed
and redirect_after_already_subscribed
fields. After a visitor subscribes, they’ll be redirect to the page with the flash message displayed.
The :target
selector is a great way to display a message without creating a separate confirmation page or relying on JavaScript.