Home > database >  Change Language in HTML using pure CSS without javascript
Change Language in HTML using pure CSS without javascript

Time:01-27

Good Day,

How can I change language in one HTML template only using pure CSS?

I tried this:

`<html>
<style>
    body.en :lang(it) {
        display: none;
    }
    body.it :lang(en) {
        display: none;
    }
</style>

<body >
    <a href="" lang="it">it</a>
    <a href="" lang="en">en</a>

    <button onclick="document.body.className='en'">english</button>
    <button onclick="document.body.className='it'">italiano</button>
<body>
</html>`

But onclick is still a javascript if im not wrong?

CodePudding user response:

body.en [lang='it'] {
    display: none;
}
body.it [lang='en'] {
    display: none;
}

And you can toggle this by add default language class to body tag:

<body class='en'></body>

And add js:

document.querySelector('.lang-switch-button').addEventListener('click', function() {
    document.querySelector('body').classList.toggle('en')
    document.querySelector('body').classList.toggle('it')
})

CodePudding user response:

The question is about pure css. Of course one could achieve this with javascript. But there are several ways to do it with pure css.

You could use the :target selector in combination with ordinary links (instead of buttons) to choose the language like this:

.main-content {
    display: none;
}
.main-content:target {
    display: block;
}
<a href="#it">italiano</a>
<a href="#en">english</a>

<div  id="it">
...
</div>
<div  id="en">
...
</div>

Another solution is using radio boxes or in combination with the :checked selector:

.main-content {
    display: none;
}

#it:checked ~ .main-content[data-lang=it] {
    display: block;
}

#en:checked ~ .main-content[data-lang=en] {
    display: block;
}

<input type="radio" name="lang" id="it" />
<label for="it">italiano</label>
<input type="radio" name="lang" id="en" />
<label for="en">english</label>

<div  data-lang="it">
contenuto italiano
</div>
<div  data-lang="en">
english content
</div>

But if your site has large content, you should consider to separate them in individual files.

  • Related