I have a table where I show/hide a full column by jQuery via a CSS class that doesn't exist:
<table>
<thead>
<tr>
<th></th>
<th class="target"></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td class="target"></td>
<td></td>
</tr>
<tr>
<td></td>
<td class="target"></td>
<td></td>
</tr>
</tbody>
</table>
With this DOM I can do this in one line via jQuery: $('.target').css('display','none');
This works perfectly, but is it valid to use CSS classes that aren't defined? Should I create an empty class for it?
<style>.target{}</style>
Are there any side effects or is there a better way to do this?
"CSS class" is a misnomer; class is an attribute (or a property, in terms of scripting) that you assign to HTML elements. In other words, you declare classes in HTML, not CSS, so in your case the "target" class does in fact exist on those specific elements, and your markup is perfectly valid as it is.
This doesn't necessarily mean that you need to have a class declared in the HTML before you can use it in CSS either. See ruakh's comment. Whether or not a selector is valid depends entirely on the selector syntax, and CSS has its own set of rules for handling parsing errors, none of which concern the markup at all. Essentially, this means HTML and CSS are completely independent of each other in the validity aspect.1
Once you understand that, it becomes clear that there is no side effect of not defining a .target rule in your stylesheet.2 When you assign classes to your elements, you can reference those elements by those classes either in a stylesheet, or a script, or both. Neither has a dependency on the other. Instead, they both refer to the markup (or, more precisely, its DOM representation). This principle applies even if you're using JavaScript to apply styles, as you're doing in your jQuery one-liner.
When you write a CSS rule with a class selector, all you're saying is "I want to apply styles to elements that belong to this class." Similarly, when you write a script to retrieve elements by a certain class name, you're saying "I want to do things with elements that belong to this class." Whether or not there are elements that belong to the class in question is a separate issue altogether.
1 This is also why a CSS ID selector matches all elements with the given ID regardless of whether the ID appears exactly once, or multiple times (resulting in a non-conforming HTML document).
2 The only situation I'm aware of where an empty CSS rule like that is necessary is when some browsers refuse to apply certain other rules properly as the result of a bug; creating an empty rule will cause those other rules to be applied for some reason. See this answer for an example of such a bug. However this is on the CSS side and therefore should have nothing to do with the markup.
There are no ill effects to use classes which don't have styles. Indeed, that's part of the usefulness of CSS is that it's de-coupled from the markup and can style or not style elements/classes/etc. as needed.
Don't think of them as "CSS classes." Think of them as "classes" which CSS happens to also use if it needs to.
According to HTML5 specification:
A class attribute must have a value that is a set of space-separated
tokens representing the various classes that the element belongs to.
... There are no additional restrictions on the tokens authors can use in
the class attribute, but authors are encouraged to use values that
describe the nature of the content, rather than values that describe
the desired presentation of the content.
Also, in the version 4:
The class attribute has several roles in HTML:
As a style sheet selector (when an author wishes to assign style
information to a set of elements).
For general purpose processing by
user agents.
Your use case falls under the second scenario, which makes it a legitimate example of using a class attribute.
You can use a class which has no styles, this is entirely valid HTML.
A class referenced in a CSS file is not a definition of a class, it is used as a selector rule for styling purposes.
When you use a classname in JavaScript, it does not look at the CSS to find that class. It looks directly in the HTML code.
All that is required is that the classname is in the HTML. It does not need to be in the CSS.
In fact, many people think it's actually a good idea to keep separate classes use with CSS and Javascript, as it allows your designers and coders to work independently without getting in each other's way by using each other's classes.
(note, the above paragraph is obviously more applicable for larger projects, so don't feel that you have to go to this extreme if you're working on your own; I mentioned it to make the point that the two can be entirely separate)
You can use CSS classes without using it, but I suggest that if you are adding CSS classes just for the JavaScript/jQuery code, prefix with it js-YourClassName so the front-end developers never use these classes to style the elements. They should understand that these classes can be removed at any time.
The moment you add the Class in your HTML the Class will be defined, so your solution is completely fine
It's not necessary to define CSS classes in your stylesheet. It should work just fine. However, adding it won't harm.
One thing that nobody here has fully mentioned is that JavaScript (aided by jQuery in this case) isn't able to directly modify a document's cascading style sheet. jQuery's css() method merely changes the matched set of elements' style property. CSS and JavaScript are completely unrelated in this aspect.
$('.target').css('display','none'); doesn't change your .target { } CSS declaration at all. What has happened here instead is that any element with a class of "target" now looks something like this:
<element class="target" style="display:none;"></element>
Are there any side effects caused by not pre-defining a CSS style rule? None whatsoever.
Is there a better way to do this? Performance-wise, yes there is!
How can the performance be improved?
Rather than directly modifying the style of each element, instead you can pre-define a new class and add that to your matched elements using addClass() (another jQuery method).
Based on this pre-existing JSPerf which compares css() with addClass(), we can see that addClass() is actually much faster:
How can we implement this ourselves?
Firstly we can add in our new CSS declaration:
.hidden {
display: none;
}
Your HTML would remain the same, this pre-defined class is simply in place for later use.
We can now modify the JavaScript to use addClass() instead:
$('.target').addClass('hidden');
When running this code, rather than directly modifying the style property of each of your matched "target" elements, this new class will now have been added:
<element class="target hidden"></element>
With the new "hidden" class, this element will inherit the styling declared in your CSS and your element will be set to no longer display.
As is mentioned by so many others, yes, using classes with no assigned CSS is perfectly valid and rather than thinking of them as 'CSS classes' you should simply recognise the semantics of class and ID to be groups and individual elements respectively.
I wanted to chip in as I felt an important point hasn't been raised given the example. If you ever need to do visual manipulations to a variable length of elements (in this case you're using table rows) then it always makes sense to recognise that the cost of doing so through Javascript could potentially be very expensive (e.g if you have thousands of rows).
In this situation let's say we know that column 2 always has the potential to be hidden (it's a conscious function of your table) then it makes sense to design a CSS style to handle this use case.
table.target-hidden .target { display: none; }
Then rather than using JS to traverse through the DOM finding N elements we simply need to toggle a class on one (our table).
$("table").addClass("target-hidden")
By assigning the table an ID this would be even quicker and you could even just refer to the column by using the :nth-child selector which would reduce your markup further but I can't comment on efficiency. Another reason for doing this is that I hate inline styling, and will go to great lengths to eradicate it!
It will have no effect if you apply a class on a HTML element, and that class is not defined in CSS. It is a common practice and like Aamir afridi said if you are using classes for js only purpose, it is a good practice to prefix them with js- .
It is not only valid for calsses, but also for id attribute of html elements.
There's no problem at all of using classes to just query for elements. I used to give such class names the sys- prefix (for example, I'll name your class sys-target) to distinguish them from classes used for styling. This was a convention used by some microsoft developers in the past. I also noticed a growing practice of using the js- prefix for this purpose.
If you are not comfortable with using classes for purposes other than styling, I recommend using the Role.js jQuery plugin which allows you to achieve the same purpose using the role attribute, so, you may write your markup as <td role="target"> and query for it using $("#target"). The project page has good description and examples. I use this plugin for big projects because I really like keeping classes for styling purposes only.
Refer to the jQuery validation engine. Even in there we also use non-existent classes to add validation rules on the HTML attributes. So there is nothing wrong in using classes that are not actually declared in a stylesheet.
Related
Instead defining:
<div id="my-custom-element-101"></div>
I wrote:
<my-custom-element-101></my-custom-element-101>
But didn't go further to extend HTMLElement and define it. This way I get some enhanced readability and don't need to do any further coding.
Is there any potential downside to this practice?
There's no absolute downside for that, as soon as you use valid custom element notation (i.e. a name with an hyphen "-").
In this case it's just an unknown custom element.
Of course if someone else decide to define a custom element with the same name you could get into some troubles but if you own the entire code of the page it can't happen.
Also note that, in your example, your tag <my-custom-element-101> is seen as an inline element, not a block.
I've developing an app with Vue, and a third-party template, and dynamic plugins, and all kinds of trickery. I'm have a really hard time with the CSS.
Often I need to style particular element on the page, an <input> for example, and I can't figure out how to write a selector that actually works. The input may have been created dynamically by some Javascript and may have had CSS applied programmatically.
So I go to Firefox Web Developer, click on the element, and see a bunch of CSS classes. I create a rule:
.myCustomClass {
color: red;
}
put myCustomClass in the class="" tag in the <input>, and... nothing.
I'm thinking I need to prefix it like this:
.someOuterClass .someInnerClass .myCustomClass {
color: red;
}
but that rarely works. Sometimes I give up and add !important. Sometimes that works, and sometimes it doesn't.
So my question is, can I examine the classes that I can see in Web Developer and somehow derive a rule that is specific enough that it will always work?
I've read about specificity, but it's not helping.
Specificity is a PITA sometimes, especially when other 3rd party libraries are adding stuff to the mix.
Here are a few things you can try:
Make sure to add your styles to the END of the CSS. Theoretically, you can affect the order Webpack includes CSS (I've never tried it)
Add an ID not a class to a wrapper outside the elements you want to change. Then reference this ID in the CSS chain eg: #myAppID .className .subClassName {} Basically ID's are stronger than classes in CSS specificity. I would try to do this at a page/view level to make life easier.
If elements are already getting classes (as you see them in the inspector) try to reuse those classes with your "override" CSS. If the classes are modularized (Have a random suffix like someClass__34xft5) you shouldn't use those exact classes since they can change if the source is recompiled. In that case, use a "matching" selector [class^=”someClass__”] to match any selector with that prefix.
Not sure how deep you want to go, but here's an article about overriding Amplify-Vue prebuilt styling.
One caveat, if the CSS is being added inline via javascript somewhere, it's going to be very hard to override. You may want to use !important in conjunction with the above.
"...can I examine the classes that I can see in Web Developer and somehow derive a rule that is specific enough that it will always work?"
Probably, but why bother? You're already adding class attributes to elements. Why not add inline style attributes instead? Adding a bunch of classes or ids just to create a specificity chain to touch up styles is pretty messy...inline styles are barely if at all worse and are clearer to understand.
Inline attributes are the most specific CSS instructions you can give.
This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 8 years ago.
Lately I'm working with a lot of Wordpress themes. When I have to edit a particular element, I usually use Firebug to see the element's name so I can change the CSS. I think I understand the difference between IDs and Classes, Classes are used for a group of elements that you want to share the same styling, and ID is usually used for a single element.
Here's the thing, I'm seeing so many elements in these Wordpress themes that are only used once, but they are assigned to a class. A good example is the website logo. Isn't the logo only used once? Shouldn't it be assigned to an ID? Why is it always assigned to a class?
Needs change often. An element/style that today you think will only be used once may be used multiple times in the future. Maybe you will have your logo more than one time on your site (for example, on your about us page). Perhaps you may eventually incorporate a second search bar. There are very few cases where you know with 100% certainty that the style will only be needed once.
Here's a good read on the subject: http://oli.jp/2011/ids/
http://ryanfait.com/articles/the-difference-between-ids-and-classes/
Ryan says
"I take a different stance than most web designers when it comes to
using ID's and classes. The vast majority of CSS coders use ID's for
any elements that are simply used once on a page. However, I only use
classes to style my websites, but, when I want to use an element in
JavaScript, I use an identifier. From a presentational standpoint,
styling elements with classes looks exactly the same as styling them
with ID's, but the flexibility of classes offers a certain appeal even
if I don't plan on using a class more than once on a page. Also, when
I see an ID in my XHTML, it reminds me that there is some JavaScript
that refers to that element. It's up to you, but so long as you
implement classes and ID's properly, it is more or less a matter of
personal choice when to utilize one or the other."
id is a unique one, but when class its not, you can you one for many selectors
ID's are unique
Each element can have only one ID
Each page can have only one element with that ID
Classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Any styling information that needs to be applied to multiple objects
on a page should be done with a class. Take for example a page with multiple "widgets":
There are some reasons why people prefer using classes instead of id's in CSS. (note that for javascript ID's are still commonly used).
The class element is re-usable on that page. This means that you won't have as much duplicated code with Classes as you would have with ID's.
Usually, IDs refer to something very specific, and abstracting would be tough
Any performance gains picked up by using id, is negated by adding any other selector to the left fo that id. Which mainly means that in most uses of id's you won't really have performance gains. (you could even have less performance than if you would just use a class)
Lecture about this:
http://screwlewse.com/2010/07/dont-use-id-selectors-in-css/
http://www.impressivewebs.com/css-specificity-irrelevant/
http://www.baldurbjarnason.com/notes/ids-in-css/
If you're new to web development, just use the simple rule:
If you're trying to apply style to a HTML element, use a class.
If you're trying to interact with a HTML element with javascript, use an ID.
You see more of classes because they can be reused and assigned to multiple elements.
However an id can belong to only one element at a time hence less of them.
Classes only appearing once:
Such cases like the one you identified, you may call them semantically incorrect as id is more appropriate choice for that but still it would work and it probably happens couple of times that we get to use class which only appearing once (may be while defining that class we are thinking that we can use it somewhere also but at the end we really dont), beside general habit another reason could be:
That class styling is also used somewhere else along with another class for e.g.:
.logo{
width:250px;
height:250px;
float:left;
}
.logo class is applied to logo <div class='logo'>...</div> But there is another element which also require same three properties of logo and some other also so one can reuse logo there also.
<div class='otherstyle logo'>...</div> this would apply the style of logo as well as otherstyle to it.
In some other words to sum it up. The cardinality of a class is 1...* so you can use it one and more than one time. But for id it is 1...1 you will and only use it only once.
I want to know what things can be done "ONLY" with CSS , that are not available using dynamically updated style "attributes" using Javascript. So far I know:
Media queries
Pseudo tags
Any more?
Update:
This question was closed but I asked it as I am trying to decide on the technology to use for a project, but one of the options cannot use CSS style sheets, and can only manipulate the style attribute using javascript.
Inline style attributes can only contain property declarations (e.g. width: 10px or color: red). They can't contain any other CSS constructs: not selectors, at-rules (e.g. #import, #media, #font-face), etc. Just property declarations.
However, they play a big role in the cascade: any styles for an element with that attribute take highest precedence (after considering !important of course).
There's actually an entire module devoted to style attributes, by the way, but it's not essential reading for authors.
So, anything that isn't a CSS declaration, is only possible in a stylesheet, not a style attribute. Not sure if that's what you're asking...
Note that media queries and #media rules are not the same thing; media queries can exist in areas outside of stylesheets too, like HTML's media attribute, where they're next most commonly found.
I believe pseudo classes (:hover etc..) and pseudo elements (:after, :before) cannot be added/manipulated via JS (via the style property i mean) because they are not part of the DOM.
I can imagine it can get complicated fast trying to debug style issues when there are multiple classes associated with elements. Currently I'm using multiple classes but in a way that one type of class is for jQuery manipulation and the other is for style. So I can have an element
<div id='myDiv' class'ActionControl SearchBox'></div>
where the .ActionControl is used by jQuery and the .SearchBox has a style associated in the CSS file. Is this right or wrong? What do people more experienced with this think?
What issues have other people come up against? How have they been resolved?
As long as your code is comprehensible, maintainable and clear to others, your system is good.
There is no standard I am aware of in how to give CSS classes, except one:
If you need to target a single element in the page using JS or CSS you should use an ID and not CLASS.
This is definitely a good practice...
What you have to keep in mind always is not to remove the class attribute, instead you will be removing the classes you exactly want to remove.
Also, another problem (not for me) is that multiple classes are not supported for OLDER browsers.
Keep in mind to code your CSS in a way it prevent code duplication so a float:left class can be used in many different elements, this is to keep code clear.
I can't see anything wrong with that. Probably, you could prefix the jQuery classes with e.g. jActionControl, so you have a better overview over who uses what classe if it gets really ugly with many classes.
Of course, you can assign as many classes as you want so there is nothing wrong with your approach in my eyes.
Another way to use multiple classes is to get a kind of inheritance.
.thing { ..blah.. }
.thing.subthing { ..tweaks.. }
<div class="thing"></div>
<div class="thing"></div>
<div class="thing subthing"></div>
Here all the things get "blah" applied to them, but only the subthing div gets the tweaks.
Yes, it can get complicated. As with any power tool, you need to apply it judiciously and with discipline.