1

I have a CSS class and I wish to set it's width attribute:

ul.month-wrapper li
{
    font-size: 13px;
}
ul.year-wrapper li
{
    font-size: 16px;
}

And the Jquery:

var MonthWidth = 30;
var YearWidth = MonthWidth * 12;

// Set CSS classes widths
$('ul.month-wrapper li').css('width', MonthWidth + 'px');
$('ul.year-wrapper li').css('width', YearWidth + 'px');

However this doesn't seem to do anything, widths remain unchanged! Any ideas?

14
  • 2
    You forgot to accept my previous answer by the way :P Commented Jul 26, 2011 at 9:27
  • Cannot reproduce: jsfiddle.net/rKePw Commented Jul 26, 2011 at 9:28
  • Just a hint, but you really don't need the 'px' when setting css attributes with jQuery. Commented Jul 26, 2011 at 9:29
  • are you sure there are no other width marked as !important already being set? Commented Jul 26, 2011 at 9:30
  • 1
    @Felix King: it looks a lot wider than 30px Commented Jul 26, 2011 at 9:32

2 Answers 2

3

You can't add anything to a CSS class. The CSS class is static.

What you are doing above is adding the width style attribute to any controls on the page which are li within a ul with the class .year-wrapper

My guess is your running this script too soon in the page script, before the List Items have loaded into the page. Try the following to ensure the page has finished loading:

$(document).ready(function(){
   var MonthWidth = 30;
   var YearWidth = MonthWidth * 12;

   // Set CSS classes widths
   $('ul.month-wrapper li').css('width', MonthWidth + 'px');
   $('ul.year-wrapper li').css('width', YearWidth + 'px');

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

2 Comments

This is correct thank you, my code was before the li's were generated, not after.
CSS classes aren't static. You can modify them with javascript, just not with jQuery specifically.
2

If you actually want to modify the classes you can use ordinary plain old Javascript, but there's nothing in jQuery to make it easier:

var ss = document.styleSheets[0];
if(ss.insertRule){
    ss.insertRule('ul.month-wrapper li {width: '+MonthWidth + 'px }', ss.cssRules.length);
    ss.insertRule('ul.year-wrapper li {width: '+YearWidth + 'px }', ss.cssRules.length);
}else if(ss.addRule){ // For IE only
    ss.addRule('ul.month-wrapper li', 'width: '+MonthWidth + 'px');
    ss.addRule('ul.year-wrapper li', 'width: '+YearWidth + 'px');
}

Example of cross browser adding rules to css class:

http://jsfiddle.net/Paulpro/sMBeq/

That's just a simple example btw which appends new rules into the stylsheet. If you want to access the current rules and just add the width: style to them it get's slightly more complicated.

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.