Nikhil Bharadwaj
Nikhil Bharadwaj

Reputation: 917

How to toggle between two texts using css

I have two language selector on the top right corner of the screen like EN | FR. When the user clicks the EN the color and text decoration of the EN text should get changed.When the useer clicks on the FR the text decoration and color and also the EN should get back to its original color and text decoration.The functions should toggle.

Is there any way to achive it using HTML and CSS only?

Upvotes: 0

Views: 352

Answers (2)

Hashem Qolami
Hashem Qolami

Reputation: 99544

One option is to use :focus pseudo-class over the elements containing EN/FR. In this case, elements should have the ability to receive focus. A possible solution is to give that elements a tabindex attribute:

span {
  display: inline-block;
  padding: .5rem;
  background: gold;
  outline: 0;
  cursor: pointer;
}

span:focus {
  background-color: tomato;
  color: white;
}
<span tabindex="-1">EN</span>
<span tabindex="-1">FR</span>

Note that :focus is applied as long as the user doesn't click on elsewhere on the page.

Also it's worth noting that :focus is well supported in legacy web browsers.


Another option is to use radio button hack with :checked pseudo-class to toggle the styles:

label {
  display: inline-block;
  padding: .5rem;
  background: gold;
  cursor: pointer;
}

input[id^="lang_"] {
  display: none;
}

input[id^="lang_"]:checked + label {
  background-color: tomato;
  color: white;
}
<input type="radio" id="lang_en" name="language">
<label for="lang_en">EN</label>

<input type="radio" id="lang_fr" name="language">
<label for="lang_fr">FR</label>

:checked pseudo-class is supported in IE9+.

Upvotes: 1

John Fisher
John Fisher

Reputation: 22717

If clicking EN or FR actually loads a new page, then you can do this with only CSS and HTML. You would specify class="en" or class="fr" in the appropriate HTML location. Then the CSS can easily apply at the right times.

However, if you are not loading a new page when the user clicks those items, you will need JavaScript. It could change the class for you, and the same CSS could work.

Upvotes: 0

Related Questions