0

What would be the best way to combine these CSS elements?

As my web page grows I'm quite concerned about maintenance. There is not much difference between the below, apart from the bg image used, so I was wondering if there could be a way to make the code more maintainable.

#section3 {
    background: url(../img/img2.jpg) no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    position: relative;
    z-index: 1;
}
@media only screen and (min-width: 0px) and (max-width: 768px) {
    #section3 {
        height: 30em; 
    }
}
@media only screen and (min-width: 769px) {
    #section3 {
        height: 50em;
    }
}

#section5 {
    background: url(../img/img3.jpg) no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    position: relative;
    z-index: 1;
}
@media only screen and (min-width: 0px) and (max-width: 768px) {
    #section5 {
        height: 30em; 
    }
}
@media only screen and (min-width: 769px) {
    #section5 {
        height: 50em;
    }
}

#section7 {
    background: url(../img/img4.jpg) no-repeat center center;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    position: relative;
    z-index: 1;
}
@media only screen and (min-width: 0px) and (max-width: 768px) {
    #section7 {
        height: 30em; 
    }
}
@media only screen and (min-width: 769px) {
    #section7 {
        height: 50em;
    }
}
1
  • Consider using SASS/SCSS, which allows CSS nesting and repeatable functions. Commented Oct 26, 2014 at 15:10

1 Answer 1

2

I would suggest something like this Fiddle.

#section3 {
    background: url(../img/img2.jpg) no-repeat center center;
}

#section5 {
    background: url(../img/img3.jpg) no-repeat center center;
}

#section7 {
    background: url(../img/img4.jpg) no-repeat center center;
}

#section7, #section5, #section3 {
     -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    position: relative;
    z-index: 1;
}

@media only screen and (min-width: 0px) and (max-width: 768px) {
    #section7, #section5, #section3 {
        height: 30em; 
    }
}
@media only screen and (min-width: 769px) {
    #section7, #section5, #section3 {
        height: 50em;
    }
}


Perhaps you have also a look at LESS or SASS.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.