Henrique Barcelos
Henrique Barcelos

Reputation: 489

How to add CSS effect in a sibling when focusing a non parent element

I know CSS doesn't work backwards, but I'm trying to show a message when the user clicks the input by changing its opacity.

But I'd like to do with :focus attribute, so the user will only see the message if it clicks que input.

I have but it doesn't work:

.td_search_subtitle {
  opacity: 0;
}

.td-search-form-widget .td-widget-search-input:focus .td_search_subtitle {
  opacity: 1
}
<form method="get" class="td-search-form-widget" action="https://example.com/">
  <div role="search">
    <input class="td-widget-search-input" type="text" value="ariana" name="s" id="s">
    <input class="wpb_button wpb_btn-inverse btn" type="submit" id="searchsubmit" value="Search">
  </div>

  <div class="td_search_subtitle">Message should appear here</div>
</form>

How can I achieve that? I'm confused, because the subtitle is actually a sibling of the form.

Upvotes: 0

Views: 41

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371168

You can use :focus-within on the parent and + (selects the next sibling):

.td_search_subtitle {
  opacity: 0;
}
div[role="search"]:focus-within + .td_search_subtitle {
  opacity: 1;
}
<form method="get" class="td-search-form-widget" action="https://example.com/">
  <div role="search">
    <input class="td-widget-search-input" type="text" value="ariana" name="s" id="s">
    <input class="wpb_button wpb_btn-inverse btn" type="submit" id="searchsubmit" value="Search">
  </div>

  <div class="td_search_subtitle">Message should appear here</div>
</form>

Upvotes: 3

Related Questions