I'm wondering if there is a way to shorten repetitive css code which only different by the given url.
the class is always named .bg-login-[n]
and the url represents the same number.
The solution I'm consindering is to somehow combine CSS and JS to loop through an array of filenames. is there a simpler or "cleaner" way?
for example:
.bg-login-1{
background: url(/images/login/login-1.jpg) no-repeat center center;
}
.bg-login-2{
background: url(/images/login/login-2.jpg) no-repeat center center;
}
.bg-login-3{
background: url(/images/login/login-3.jpg) no-repeat center center;
}
.bg-login-4{
background: url(/images/login/login-4.jpg) no-repeat center center;
}
.bg-login-5{
background: url(/images/login/login-5.jpg) no-repeat center center;
}
CodePudding user response:
No JS needed. Just repeat numbers or use SCSS for loop.
.bg {
background-position: center center;
background-repeat: no-repeat:
}
.bg-1 {
background-image: url(/images/login/login-1.jpg);
}
.bg-2 {
background-image: url(/images/login/login-2.jpg);
}
/* ... */
/* SCSS */
@for $i from 1 through N {
.bg-#{$i} {
background-image: url(/images/login/login-#{$i}.jpg);
}
}
CodePudding user response:
.bg-login-1 {
background-image: url(/images/login/login-1.jpg);
}
.bg-login-2 {
background-image: url(/images/login/login-2.jpg);
}
.bg-login-3 {
background-image: url(/images/login/login-3.jpg);
}
.bg-login-4 {
background-image: url(/images/login/login-4.jpg);
}
.bg-login-5 {
background-image: url(/images/login/login-5.jpg);
}
And for the last three properties, do this:
.bg-login-1,
.bg-login-2,
.bg-login-3,
.bg-login-4,
.bg-login-5 {
background-repeat: no-repeat;
background-position: center;
}
or do this:
.bg-login {
background-repeat: no-repeat;
background-position: center;
}
CodePudding user response:
Add classname bg-login
to all the button.
<script>
const btns = document.getElementsByClassName('bg-login'); //get all the buttons
const i=1;
for(const btn in btns){
btn.style.backgroundImage = `url(/images/login/login-${i}.jpg) no-repeat center center`;
i ;
}
</script>
CodePudding user response:
Maybe you can try something like this (in you JS):
for (let i = 1; i<=5; i ) {
let bg = document.querySelector(`bg-login-${i}`)
bg.style.background = `url(/images/login/login-${i}.jpg) no-repeat center center;`;
}