What do square brackets in class names mean? - html

I saw here square brackets that are used in class names:
<input class="validate[required,custom[onlyLetter],length[0,100]]" name="firstname" type="text" />
What do these square brackets mean?

The square brackets are used as an attribute selector, to select all elements that have a certain attribute value. In other words, they detect attribute presence.
Example 1:
img[alt="picName"] {width:100px;}
would affect only
<img src="picName.png" alt="picName" />
in your code, and won't affect
<img src="picName.png" alt="picName2" />
Example 2:
The following affects all elements with title attribute specified:
[title] {border:1px dotted #333;}
Example 3:
This CSS
p[class~="fancy"]
will affect the following html
<p class="fancy">Hello</p>
<p class="very fancy">Hola</p>
<p class="fancy maybe">Aloha</p>
but won't affect this:
<p class="fancy-fancy">Privet</p>
Example 4:
[lang|="en"]
will affect elements with lang attribute, which is hyphen-separated list of words beginning with “en”, like
<div lang="en">Tere</div>
<div lang="en-gb">GutenTag</div>
Examples 5, 6, 7:(CSS3)
The following attribute selector affects link elements whose href attribute value starts with the string “http:”.
a[href^="http:"]
The following attribute selector affects image elements whose src attribute values ends with the string “.png”.
img[src$=".png"]
The following attribute selector affects any input element whose name attribute value contains the string “choice”.
input[name*="choice"]

That is most likely used by some sort of validator or validation library. The class here means that validate this field denoted by validate keyword and then:
required it is required field
custom validation type; allow only letters
length should be between 0 to 100 chars
Well, this information is used by the jQuery validation library you posted the link to :)

Apart from the use-case / example given by the OP for brackets in class names, there is also another use case which Harry Roberts proposed (and later stopped proposing) in his blog a while back: grouping related classes in your markup where the square brackets could be used to group
two or more related class attributes to make them easier to notice
when scanning an HTML file
...
and that looks something like this:
<div class="[ foo foo--bar ] baz">
where:
There must be more than one ‘set’ of classes.
One ‘set’ must contain more than one class.
He also noted that adding the brackets is completely valid according to the html5 spec
There are no […] restrictions on the tokens authors can use in the
class attribute…
Just to reiterate:
The brackets in the class attributes - while being valid CSS class names are not actually meant to be used in the CSS1 - but rather to help readability in the HTML.
Notes:
1
Although technically, they can be used when escaped,
.\[ {
color: red;
}
<div class="[">Hi there</div>

Nothing. Brackets are a legal character for class names with no special meaning whatsoever.

In standard HTML, they have no particular meaning. It's just more text.
To the jQuery Validation plugin, they do.

Example:
[what-ever] {
color: red;
}
<p what-ever>Hello</p>
This will color Hello red. You can use square-bracket as class names

There is no particular rule within a class name. In your example they are almost certainly being used by a JavaScript validation framework. This is because in HTML you can't simply add your own attributes to tags, therefore the validation framework is exploiting the fact that CSS class names can contain such characters in order to 'store' the validation rules within the class name. There won't actually be any corresponding class in the style-sheet - this is just a trick to work around the limitations of HTML.

Related

What does a reference inside a div tag without an attribute do?

I would like to start using Attribute Selectors in my css. I am seeing div tags that contain a reference WITHOUT any attribute statement like:
<div class="container" data-footer>
All my searches (for the last hour) to find out how "data-footer" can be listed without the use of an attribute= (e.g., id= or class= or etc.) have resulted in no information. Dozens of SO and Google links without a single example of a reference inside a div tag without the use of an attribute. Because I do not know what this is (or what to call it) I'm probably not searching with the right keywords. Is this a short-form way to pass an id or ???
Data- attributes without a value can be used as Boolean. For example:
if(div.hasAttribute('data-footer')) {
// then do something
}
In css you can access it like:
div[data-footer] {
}

Terminology - The types of elements in HTML

A while ago there was a term that I remembered that described two categories of elements. I forgot the term and I want to know what that term was. The information I can remember is that the first category of elements get their values from within HTML like <p> or <a> or <ul> but there is another category of elements which get their values from "outside" of HTML like <img> or <input type="textbox">. I want to know the terminology for these types.
Edit - I've went through Zomry, Difster and BoltClock's answers and didn't get anything. So I remembered some extra piece of information and decided to add it. The two categories are Lazy Opposites of each other. For example if one is called xyz, then the other is called non-xyz.
Probably you mean replaced elements (and non-replaced, respectively)?
However, the distinction between them is not so unambigous. For example, form controls were traditionally considered replaced elements, but the HTML spec currently explicitly lists them as non-replaced (introducing the "widget" term instead).
The HTML specification mentions for tags like <img> and <input> the following: Tag omission in text/html: No end tag.
Tags with an end tag are defined as: Tag omission in text/html: Neither tag is omissible.
So as far as I can find, the HTML spec does define a technical name for this, apart from void versus normal elements, so what Watilin pointed out in the comments should be fine: standalone vs containers.
As an added side-note: HTML has a lot more HTML content categories. You can find a complete overview at the HTML spec here: https://html.spec.whatwg.org/multipage/indices.html#element-content-categories
Also interesting to read to visualize that a bit better: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories
Elements whose contents are defined by text and/or other elements between their start and end tags don't have a special category. Even the HTML spec just calls them normal elements for the most part in section 8.1.2.
Elements whose primary values are defined by attributes and that cannot have content between their tags are called void elements. img and input are indeed two examples of void elements. Note that void elements are not to be confused with empty elements; see the following questions for more details on that:
Are void elements and empty elements the same?
HTML "void elements" so called because without content?
<input type="text" id="someField" name="someField">
With an input selector, you can get a value from it like so (with jQuery):
$("#someField).val();
Where as with a paragraph or a div, you don't get a value, you get the text or html.
<div id="someDiv">Blah, blah, blah</div> You can get that with jQuery as follows:
$("#someDiv").html();
Do you see the difference?

CSS classes with special characters

I have a WebApp where I need to manipulate certain elements using a CSS file. The CSS classes contain square brackets and other special characters. At least chrome doesn't seem to accept them directly.
<div class="profileElement profile[~redString]">123</div>
Is this class even valid? Is there a way to use the classname? I want:
.profile[~redString]{
color: red; }
When I escape the ~ with a backslash chrome allows me to inject (F12 -> Elements -> the plus symbol on the top right) it to the page but displays the css in grey, meaning the class does not exist in the page.
Is that class valid?
If so, how would I use it?
Is this class even valid?
It depends on what you're validating against.
profile[~redString] is a valid HTML class name, exemplified by putting the markup through a validator.
However, .profile[~redString] is not a valid CSS selector, because the ~ is a special symbol as you have found out, and it's not in a place where the CSS parser would expect it. When you escape it, you get
.profile[\~redString]
which is a valid selector, but with a completely different meaning. It represents an element with a class name profile, as well as an attribute called ~redString. It does not represent an element with a class name that is exactly profile[~redString].
To match this element, you need to escape the square brackets as well. This will result in the entire stream of characters being treated as a single identifier:
.profile\[\~redString\]
Alternatively, you can use an attribute selector instead to make things cleaner:
[class~="profile[~redString]"]
Notice the ~= in this CSS2.1 attribute selector, which works similarly to a class selector.
See both selectors in action:
:first-child.profile\[\~redString\],
:last-child[class~="profile[~redString]"] {
color: red;
}
<div>
<div class="profileElement profile[~redString]">123</div>
<div class="profileElement profile[~redString]">456</div>
</div>

Is adding a css class to a <b> tag valid html/css

Is adding a css class to a <b> tag valid html/css
Example, can I do this:
<b class="myclass"> Foo Bar </b>
Is this valid html/css?
I need to add a class to a b tag as an identifier so I can use it in jQuery/js. It wont have any css styles
Yes, b tag can have all global attributes, including class.
The full list of attributes, you can add to b element:
accesskey
class
contenteditable
contextmenu
dir
draggable
dropzone
hidden
id
inert
itemid
itemprop
itemref
itemscope
itemtype
lang
spellcheck
style
tabindex
title
translate
You can also use any custom data attributes.
Finally, you can add also ARIA role attribute.
Of course. There's nothing wrong with that.
However, it's generally a bad idea to use class purely for identifying an element. Consider using something like data-reference or something, as this will be more correct (and more efficient on the browser not having to keep track of a class that's not used as a class)
Yes, this is perfectly valid. Absolutely nothing wrong with it.
There's nothing strictly wrong with it, except that the <b> bold tag is deprecated, in favor of using the <strong> tag.
I never give the strong (or b) tag a class because I only use it when I want the text strong to call attention to it, similar to <em> emphasizing words in text.
If I am bolding or emphasizing the text for some other reason I use a div or span with a class — for example, it is common to italicize the title of a book or article, and in that case I do not use <em> around the title, I use <span class="title">This Is That Title</span> to semantically mark what this thing is, then use a stylesheet to say "titles are italic".
There are no “CSS classes”. CSS has class selectors, but that’s a different issue and postulates the existence of a class attribute in a markup language. Thus, the question is meaningless as far as CSS is considered.
In HTML, the class attribute is valid (formally correct) on b elements, in any HTML version from HTML 4.0 (which introduced the attribute) onwards. Whether it makes sense or not is a different issue, but there are no formal restrictions on its use. Although class is most often used for styling, it can be used for other purposes, too, especially in scripting.

CSS selector with period in ID

The HTML spec allows for periods (.) in an id:
<img id="some.id" />
However, using a CSS ID selector rule will not match correctly:
#some.id { color: #f00; }
The CSS spec for ID Selectors does not mention this case. So I assume it is using the combination of a tag name and class selector? For example, a CSS rule of a.className would apply to all anchor tags (<a>) with a class name of className, like <a class="className"></a>.
Is it possible to have an external CSS file rule that references an HTML element by its id that has a period in it?
I expect not since the CSS spec specifies that a CSS "identifier" does not include the period as a valid character. So is this a fundamental mismatch between HTML and CSS specs? Is my only alternative to use a different type of CSS selection? Can anyone smarter than I confirm or deny this?
(I would remove the period from the HTML id attribute to simplify things, but it is a system-generated id, so I don't have the ability to change it in this case.)
After digging through the specs some more, I found the CSS spec does allow for backslash (\) escaping like most languages.
So in my example, the following rule would match:
#some\.id {
color: #f00;
}
You could also use the attribute selector like this:
[id='some.id'] {
color: #f00;
}
Since you are using id, you can also use document.getElementById() which checks the id value as a normal string and not a CSS selector.
e.g. the following works too:
const myElem = document.getElementById("some.id");
The only drawback is, you can't limit the scope of search, like you could with querySelector e.g. someElement.querySelector().
but since Ids should always be unique, a document wide search with id is valid.