How to Override a #Id Ul Li Behaviour with a Class Definition

Can I override a #id ul li behaviour with a class definition

I agree with SWilk, avoid !important if possible (and it is possible here). Some other solutions that SWilk did not offer is:

#id ul.myclass li {

or...

#id ul li.myclass {

The key is increasing the specificity of the selector, which the above, and SWilk's solutions do. The reason your original solutions did not work is that you did not include the other tag (ul or li) nor the #id with your addition of the .myclass.

Added after your comment that showed structure:

If your html is this (as you stated in your comment):

<div id="ja-col2">
<div>....
<ul class="latestnews">
<li class="latestnews">

And your current css is (as stated in another comment):

#ja-col1 ul li, 
#ja-col2 ul li {
margin:0; padding-left:15px;
}
#ja-col2 .latestnews ul li, /*does not exist*/
.latestnews #ja-col2 ul li, /*does not exist*/
.latestnews ul li, /*does not exist*/
ul.latestnews li.latestnews {
list-style:disc outside url("../images/bullet.gif");
margin-left:15px; padding-left:15px;
}
ul li { line-height:180%; margin-left:30px; }

The reason you are not seeing any change is because three of your selector paths do not exist in your html structure, and the one that wins by specificity is the very first group. You need:

#ja-col2 ul.latestnews li

To override the #ja-col2 ul li.

Override a span hover using CSS

Using two CSS IDs is incorrect. They are supposed to be unique. Use classes if you want to use styling multiple times. Always remember this, Classes are for multiple usage, IDs are for single, unique usage.

CSS - parent element overrides child element properties

You have 2 selectors: #main-content ul li and .footer-buttons ul li . First of them uses id and the second uses class, that's why the first one is used as more descriptive. Use:

#main-content .footer-buttons ul li { display: inline; }

Can't override styles set in nth-child

This is because of Specificity. Like more general rules will be overridden by more specific rules. li:nth-child is more specific than .hmm. So just increase the specificity of .hmm by adding li.hmm

li:nth-child(2n+1){  color: red;  font-weight:normal;}
li.hmm{ color:green; font-weight:bold;}
<ul><li class="hmm">HMM</li><li>test</li><li class="hmm">HMM</li><li class="hmm">HMM</li><li>test</li></ul>

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

If You Are Able to Edit the Offending Stylesheet

If the user-agent stylesheet's style is causing problems for the browser it's supposed to fix, then you could try removing the offending style and testing that to ensure it doesn't have any unexpected adverse effects elsewhere.

If it doesn't, use the modified stylesheet. Fixing browser quirks is what these sheets are for - they fix issues, they aren't supposed to introduce new ones.

If You Are Not Able to Edit the Offending Stylesheet

If you're unable to edit the stylesheet that contains the offending line, you may consider using the !important keyword.

An example:

.override {
border: 1px solid #000 !important;
}

.a_class {
border: 2px solid red;
}

And the HTML:

<p class="a_class">content will have 2px red border</p>
<p class="override a_class">content will have 1px black border</p>

Live example

Try to use !important only where you really have to - if you can reorganize your styles such that you don't need it, this would be preferable.

CSS last-child not overriding parent border

I've used your HTML and wrote minimal CSS for you to understand

TIP : Give classes and id's name which have semantic meaning to it. It is difficult to code when you give class names like these.

.gf-menu.l1 li {    display: inline-block;    padding: 0 10px 0 10px;    border-right: 1px solid red;}
.gf-menu.l1 li:last-child { border-right: none;}
<ul class="gf-menu l1 ">    <li class="item487">        <a class="item" href="link1">            menu_item_1        </a>          </li>    <li class="item488">        <a class="item" href="link2">            menu_item_2        </a>          </li>    <li class="item489">        <a class="item" href="link1">            menu_item_2        </a>          </li></ul>

Why don't media queries override normal CSS?

In theory, no - you don't need the !important flag. The issue you are probably experiencing arrises from specificity:

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors

Mozzila

The basic math (hugely simplified) behind specificity is a weighted approach.

id is worth 100,
class is worth 10,
tag is worth 1.

Therefore a.class (tag + class = 11) is less specific that a#id (tag + id = 101).

CSS is also applied in a last-match-wins format, that is to say that the style for the last declared selector that matches will be applied (sorted according to the above specificity).

So - in your example, it could be that there are elements on you page with the class .element which is being targeted with a more specific selector (such as .container div > ul li + li .element (which is a lot more specific than just .element) so the styles from that is overriding the styles from your media style.

The caveat to this, is if the !important flag is being used. In which case the only way to override the styles is to supply the !important flag again.

How can I change an element's class with JavaScript?

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') )

document.getElementById("MyElement").classList.toggle('MyClass');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace
( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character

MyClass # The literal text for the classname to remove

(?!\S) # Negative lookahead to verify the above is the whole classname
# Ensures there is no non-space character following
# (i.e. must be the end of the string or space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )


### Assigning these actions to onClick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick="this.className+=' MyClass'") this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:

<script type="text/javascript">
function changeClass(){
// Code examples from above
}
</script>
...
<button onClick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
function changeClass(){
// Code examples from above
}

window.onload = function(){
document.getElementById("MyElement").addEventListener( 'click', changeClass);
}
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)



JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50  KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

In addition, jQuery provides a shortcut for adding a class if it doesn't apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass');


### Assigning a function to a click event with jQuery:
$('#MyElement').click(changeClass);

or, without needing an id:

$(':button:contains(My Button)').click(changeClass);




Related Topics



Leave a reply



Submit