EdwardBlack EdwardBlack - 6 months ago 27
CSS Question

Change multiple CSS attributes at once

I was wondering if it is possible to change multiple CSS attributes of an element with one line?

Right now if I have an element and try to change some CSS attributes, then I have to write one line of code for each css attribute. For example:

$("p#message").css("background-color", "red");
$("p#message").css("color", "white");
$("p#message").css("padding", "5px");
$("p#message").css("width", "120px");
$("p#message").css("text-align", "center");

div#start {
background-color: #D8D8D8;
border: 1px solid black;
width: 50px;
text-align: center;

div#start:hover {
cursor: pointer;
background-color: #A1A1A1;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="message">Hi Folks</p>
<div id="start">Change CSS</div>

As you can see in my example above, I am writing one line for each CSS attribute. Is is possible to accomplish this with a single command? For example something like this:

"background-color": "red",
"color": "white",
"padding": "5px",
"width": "120px",
"text-align": "center"


Pass the object to the css(). The code is missing { and }.

    "background-color": "red",
    "color": "white",
    "padding": "5px",
    "width": "120px",
    "text-align": "center"

As the styles are fixed, i'll suggest to make a CSS class and add the class.



.myClass {
    background: red;
    color: white;
    padding: 5px;
    width: 120px;
    text-align: center