user1655072
user1655072

Reputation: 672

add css to an element with exisiting css

if I have an html element with predefined css style

<h1 style="color:blue;">This is a header</h1>

Now if I want to add a new style called text-align:center to h1 element.

How can I add a new style attribute to the end of the style attribute without overwrite the existing style?

So the result will look something like

<h1 style="color:blue;text-align:center">This is a header</h1>

Upvotes: 0

Views: 114

Answers (3)

MikeM
MikeM

Reputation: 27405

Here's three methods of doing this:

jsfiddle example

1 - set element style property - on the fly JavaScript styling, however arguably breaks separation of concerns

HTML:

<h1 id="headerExample1" style="color:blue;">This is a header</h1>

JavaScript:

var ex1 = document.getElementById('headerExample1');

if (someLogic) {
    ex1.style.textAlign = "center";
}

2 - set the style attribute - this is the dirtiest of the three but does give you an idea of how you can access/change the style property directly using JavaScript

HTML:

<h1 id="headerExample2" style="color:blue;">This is a header</h1>

JavaScript:

var ex2 = document.getElementById('headerExample2');

if (someLogic) {
    ex2.setAttribute('style', ex2.getAttribute('style') + ";text-align:center");
}

3 - CSS and classes - this is the cleanest way to style the header with regard to separation of concerns

HTML:

<h1 id="headerExample3">This is a header</h1>

CSS:

#headerExample3 {color:blue;}
.centered {text-align:center;}

​ JavaScript:

var ex3 = document.getElementById('headerExample3');

if (someLogic) {
    ex3.className = "centered";
}

Upvotes: 1

Rups
Rups

Reputation: 639

Use javascript: document.getElementById("h1id").style.textAlign = "center";

Replace the h1id above with the id you will provide in the html.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

Using inline styles is a bad idea because it is difficult to override them and maintaining separation of content and layout is important in web development.

Best to use a stylesheet:

h1 {
    color:blue;
    text-align:center
}

with JavaScript:

document.getElementsByTagName('h1').style.textAlign="center";

Upvotes: 0

Related Questions