Semantic CSS: Smart selectors semantic CSS

Source: Internet
Author: User
Tags add button type empty end functions header inheritance string
Article introduction: Semantic CSS combined with smart selectors.
"Structure is always subject to function, which is the constant law," said construction engineer Louis Sullivan, "the father of skyscrapers." Because engineers don't want innocent people to be crushed under huge buildings, this thumbs-up rule is quite useful. In design you should always focus on functionality, and then let the structure appear in the results. If you focus on structure, although this can build a beautiful skyscraper, it comes at the cost of planting many rather dangerous seeds.

These are all about architects, but what about front-end architects or "non-real architects"? Do we need to follow this rule or ignore it?

With the emergence of object-oriented CSS (OOCSS), more and more people tend to "detach the semantics of presentation from the semantics of documents". With the non-specific meaning of classes, we can manage a document and its appearance in a separate way.

Semantic CSS: Smart selectors

In this article, we will explore a variety of ways to style web documents. They can combine document semantics with visual design. Through the use of "smart" selectors, we use this method to show you how to query the existing features of semantic HTML documents as a reward for those well-formed markups. If your code is correct, you will definitely get what you expect to design.

I think that if you are developing several different projects at the same time as me, I hope that these methods will simplify your workflow and make it easier to shuttle between these projects. In addition, in the last part we will explain a more passive approach: we will make a CSS bookmarklet with attribute selectors to test those poorly written HTML documents and use pseudo elements to report errors.

Smart selector
The invention of style sheets allowed us to separate the code that beautifies HTML documents from HTML documents. But it doesn't help us write standard HTML documents. It doesn't bring higher quality TV shows to TVs like remote control. It just makes the job easier. Because we can use a selector to style multiple elements. (E.g. p works on all paragraph elements), the consistency and maintainability of the page are not as daunting as before.

The simplest form of p selector is a representative of smart selector. Because the p-selector has an innate foundation in semantic classification. Without the developer having to do anything extra, it already knows how to identify a paragraph and when to style them. It is very simple and effective, especially if you want to style all the paragraph elements produced by the WYSIWYG editor.

But if it is an intelligent selector, what are the non-intelligent selectors? All selectors that require developers to intervene and change the document to cause style changes are called non-smart selectors. class is a classic non-smart selector because it does not appear as part of the semantic convention. You have the flexibility to name and organize your classes, but you need some thought; they won't do anything automatically unless you apply them on the document.

Using non-smart selectors is very time consuming, because we need to manually add different styles for each selector and copy the class name to every element that needs to apply this class. If we don't have the p tag, we have to use non-smart selectors to manage the paragraphs, such as using a .paragraph class to indicate in each paragraph element. One of the disadvantages is that these style sheets are not portable, because you can no longer apply these styles to the required elements without specifying the corresponding class name for the tags of the HTML document.

Semantic CSS: Smart selectors

Non-smart selectors are sometimes necessary, and few of us rely entirely on smart selectors. However, some non-smart selectors may become "stupid" selectors because of a mismatch between the structure and presentation of the document. I'll talk about .button, a "stupid" selector that's used very frequently.

Benefits of different combinations
Smart selectors are not limited to the basic elements provided to us in the HTML specification. To build complex smart selectors, you can distinguish the underlying elements by following a combination of context and functional attributes. Some elements, such as <a>, provide a large number of functional differences for developers to consider and utilize. Other elements, such as the <p> element, have no obvious difference in functionality in any scenario, but they also assume slightly different roles depending on the context.

header
p
{/ * styles for prologic paragraphs * /
}
footer
p
{/ * styles for epilogic paragraphs * /
}
Hell
Simple descendant selectors like this are very useful because they allow us to visually see the different types of an element without physically changing the underlying document. This is why the entire style sheet was invented: to promote physical separation without breaking the conceptual interrelationships that exist between documents and designs.

Semantic CSS: Smart selectors

Inevitably, some OOCSS fans have a little disagreement with such descendant selectors. They prefer to mark it like the following example, which is found in the BEM "definition" document.

<ul
class = "menu">
<li
class = "menu__item"> ... </ li>
<li
class = "menu__item"> ... </ li>
</ ul>
Hell
I won't go into further discussion of descendant selectors, because I'm sure you use them every day, unless you prefer the excessive overview above. In other words, we will next focus on the differences made by the attribute selector and the features described in attributes.

Hyperlink properties
Even proponents of the conceptual separation between CSS and HTML are happy to recognize some attributes-most of them except class and custom data attributes-are actually important to the internal workings of the document. Without the href attribute your hyperlink will not link to anything. Without the type attribute, the browser cannot know which type of input element to render. Without the title attribute, your abbr element could represent anything.

Attributes like this help improve the semantics of document details, otherwise you need to verify that the theme elements are correctly rendered and functioning. If they don't exist, they should be created. If they already exist, why not apply them? You can't just write CSS but not HTML.

REL attribute

The rel attribute is a standard attribute of a link relationship and a method for describing the specific purpose of a link. Not all links function the same. Thanks to the many WordPress users, rel = "prev" and rel = "next" became the two most widely used values and helped to describe the relationship between each individual page of paginated blog content. Semantically, an a tag with a rel attribute is still an a tag, but we can already express it more specifically. This is not the same as a class, this specificity is semantically indirect.

The rel attributes should only be used where appropriate because they are maintained by the functional specifications of HTML and can therefore be adopted by different user agents to improve user experience and search engine accuracy. So, have you styled your links like this? Use simple attribute selectors, such as:

[rel = "prev"]
{/ * styling for "previous links" * /
}
[rel = "next"]
{/ * styling for "next" links * /
}
Hell
Attribute selectors are supported by all browsers except the oldest and backward browsers (IE6), so there is no reason not to use them as long as this attribute is present in the tag. In terms of its priority, it has the same weight value as the class. However, I remember it was suggested that we should separate document and presentation semantics. I don't want to waste this rel attribute, so I better set the element to a meaningless attribute and use it to add styles.

<a
href = "/ previous-article-snippet /"
rel = "prev"
class = "prev"> previous page </a>
Hell
The first thing to notice here is that the only attribute in the above element that does not help the semantics of the document is the class attribute. In other words, the class in the above document is the only thing that doesn't play a functional role. In practice, this means that the class is the only one that breaks the law of separation and is interpreted as: it actually exists in the document without any help to the structure of the document.

Okay, so many abstract concepts said, but what about its maintainability? Everyone accepts class as a style hook, let's see what happens when some attributes are removed through editing or refactoring. Suppose we use a pseudo element to add a left-pointing arrow in front of the text of the [rel = "prev"] link:

.prev: before
{content:
"\ 2190";
/ * encoding for a left-pointing arrow ("←") * /
}
Hell
Semantic CSS: Smart selectors

Removing the class also removes the pseudo-elements, which in turn will remove the arrow. But without this arrow, nothing else can tell us to link the existing prev relationship. For the same reason, removing the rel attribute can also cause the arrow to be incomplete: because the class will continue to display this arrow, it will always cause the state relationship of the document to be lost. Only by directly giving and applying styles through semantic properties can you keep your code and yourself real. As long as it is a real feature in the document, you want it to be visible.

Attribute string
I can imagine what you are thinking: "This is interesting, but how many of these semantic style hooks are there in hyperlinks? I still have to rely on classes to apply styles." Then please take a look at the different link functions below Incomplete list, all based on a element:

links to external resources,
links to secure pages,
links to author pages,
links to help pages,
links to previous pages (see example above),
links to next pages (see example above again),
links to PDF resources,
links to documents,
links to ZIP folders,
links to executables,
links to internal page fragments,
links that are really buttons (more on these later),
links that are really buttons and are toggle-able,
links that open mail clients,
links that cue up telephone numbers on smartphones,
links to the source view of pages,
links that open new tabs and windows,
links to JavaScript and JSON files,
links to RSS feeds and XML files.
This is the difference in link functionality, all types are recognized by the user agent. Now let's think about a problem. In order for all these specific link types to perform different functions, they must have different properties. In other words, in order to perform different functions, the written form of the link needs to be changed; and if they are written differently, they can add different styles through this.

In preparing this article, I tested an idea and named it Auconics. Auticons is an icon font and style sheet for automatically styling links. All the selectors in it are attribute selectors without a class, calling styles for well-formed hyperlinks.

Semantic CSS: Smart selectors

In many cases, Auticons queried a subset of href values to determine the functionality of the hyperlink. It is also possible to add styles to the corresponding elements through the beginning or end of their attribute value, or to find the corresponding element based on whether their attribute value contains a specified string. Here are some common examples.

Security Protocol Every well-formed URL (for example, an absolute URL) starts with a URI scheme followed by a colon. The most common in the network is http :, but mailTo: (for Simple Mail Transfer Protocol SMTP) and tel: (for phone numbers) are also very common. If we can know how the href value of the hyperlink will start, we can use this convention as a style hook. In the following example for a secure page, we use the ^ = comparator, which means "start with".

[href ^ = "https:"]

{/ * style properties exclusive to secure pages * /
}
Hell
Semantic CSS: Smart selectors

In Auticons, links to secure pages are decorated with a lock based on a specific semantic pattern used to identify the href attribute. The advantages of this are:

A link to a secure page-and just a secure page-can be made like a secure page link with a padlock.
Links that no longer link to secure pages lose the http protocol and padlocks used as metaphors disappear.
Links to new secure pages will also automatically use this padlock to mark the link.
This selector is quite smart when applied to dynamic content. Because a secure link has its specific URI scheme, the attribute selector can anticipate its invocation: once the editor types something that contains a secure link, the link will automatically apply styles to give the user the feeling that it is a secure link. Since no classes and editing of HTML is needed, the link in simple Markdown looks like this:

[Link to secure page] (https://payment.example.com/)
Hell
But be aware that using [href ^ = "https:"] is not always correct, because not all HTTPS is truly secure. However, this is only when the browser itself is less reliable. Professional browsers will render a padlock in the address bar when displaying HTTPS.

Semantic CSS: Smart selectors

file type

As I said, you can also style hyperlinks by what the href attribute ends with. In practice, this means that you can use CSS to indicate the type of file that the link points to. Auticons supports .txt, .pdf, .doc, .exe and other formats. The following is an example of the .zip format. Use $ = to determine what href ends in:

[href $ = ". zip"]: before, [href $ = ". gz"]: before
{content:
"\ E004";
/ * unicode for the zip folder icon * /
}
Hell
combination

Do you know how to add multiple class methods to an element to style it? Great, in fact you can use attribute selectors to help you automate these tasks. Let's compare them:

/ * The CSS for the class approach * /
.new-window-icon: after
{content:
"[new window icon]";
}
.twitter-icon: before
{content:
"[twitter icon]";
}
/ * The CSS for the attribute selector approach * /
[target = "_ blank"]: after
{content:
"[new window icon]";
}
[href * = "twitter.com/"]:before
{content:
"[twitter icon]";
}
Hell
(Note that * = comparator means "content", if the href value contains the string twitter.com/, then the style should be on that element)

<!-The HTML for the class approach->
<a
href = "http://twitter.com/heydonworks"
target = "_ blank"
class = "new-window-icon twitter-icon"> @ heydonworks </a>
<!-The HTML for the attribute selector approach->
<a
href = "http://twitter.com/heydonworks"
target = "_ blank"> @ heydonworks </a>
Hell
Semantic CSS: Smart selectors

Any content editor responsible for adding a hyperlink to a Twitter page now only needs to know two things: the URL and how to open it in a new tab. Because the attribute selector can help them find the corresponding hyperlink.

inherit

There are other things that are not taken into account: What if there is a link that does not match any attribute selector? What if this hyperlink is a plain old hyperlink? This selector is an easy-to-remember and extreme performance enthusiast who will be happy to hear the words "There is nothing more concise than it is."

Semantic CSS: Smart selectors

The inheritance of cascading property selectors is the same as when cascading with classes. First, it will style your a-assuming a text-decoration: underline rule to improve the accessibility of the link; then use the attribute selector you provided to further add a cascading style to the corresponding a element. Browsers like IE7 do not fully support pseudo-elements. But because of inheritance, the link will still apply the style in a selector.

a
{color: blue;
text-decoration: underline;
}
a [rel = "external"]: after
{content:
"[icon for external links]";
}
Hell
The actual button should be real
In the following sections, we will detail the structure of our CSS bookmarks to explain code errors. Before doing this, let's first take a look at what might be a bad selector sneaking into our workflow.

OOCSS followers still insist on using classes because they are reusable, just like components. Therefore, .button is better than #button. However, I can think of a better button style selector. Its name is also easy to remember.

Semantic CSS: Smart selectors

 
The <buttonelement represents a button. – W3C Wiki

 
Topcoat is a OOCSS BEM-based UI framework from Adobe. The various button style codes in Topcoat are more than 450 lines, if the comment block is also included. The comment block inside suggests that we apply the style of the button in a way similar to this example.

<a
class = "topcoat-button"> Button </a>
Hell
This is not a button. Because if it is a button, it should be labeled using <button>. In fact, in every known browser, if you use <button> to represent a button without adding any style, it will also look like a button by default. But the above example is not, because it uses the <a> tag, which should represent a hyperlink. In fact, it lacks an href, which means it is not even a hyperlink. Technically, it's just a placeholder, an incomplete hyperlink that is not complete.

Semantic CSS: Smart selectors
A puppy in a shark costume is not a shark

The example in Topcoat's CSS is just an example, but only if the class defines the element and the HTML is not deceptive (you should use the button tag instead of the a tag to describe the button). Adding more "meaningful hyphenation" class names will not make up for your ugly use of non-smart selectors and code errors.

Update: As of writing this article, Topcoat.io has replaced the above example with the <button> tag. This is simply amazing! However, I have reservations about using the .is-disabled class to indicate that the button is disabled and ignore the disabled attribute. You can see my discussion with Topcoat representatives in this area in the comments section. To the disaster of promoting the WEB standards brought by OOCSS, you can find it yourself at semantic-ui.com. The "standard button" in their example is actually a <div> tag containing an empty <i> tag.

See what it is

 
"If it looks like a duck, swims like a duck, and barks like a duck, it might be a duck."

 
A button decorated like a button, and also triggering Javascript events like clicking a button, for many people, it is a button. However, this only means that it has passed the "duck test" of the first two stages. In order for all users to use inductive reasoning and discrimination buttons, it must also be like this. Because it is still a link, try to avoid this unnecessary confusion, because the users of this assistive technology do not pursue a perfect semantics, but this is exactly our responsibility.

However, some people insist on using a as the label for the button. A hyperlink is an element that can be easily restyled completely. If you select the a tag as the element, there is only one way to get it closer to the real button. You guessed it: you must use the WAI ARIA role attribute value to indicate what it means. You can confirm that a hyperlink looks like a button for some reason just by the following property selector.

[role = "button"]
{/ * semantic CSS for modified elements that are announced as “button” in assistive technologies * /
}
Hell
Quality Assurance Attribute Selector
 
"CSS gives the class attribute a powerful power. Authors can design their" document language "based on those elements without any expression (such as DIV and SPAN) and give them style information through the class attribute. Authors should avoid this. This behavior even the structural elements of this document language are often recognized and accepted for their meaning. "–" Selector, "CSS Level 2, W3C

 
The reason we have a and button elements is to semantically divide two completely different functional interactions. Hyperlinks represent symbols where you will go, and buttons are used as trigger sources for events or actions. One is about location movement and the other is about conversion. One promotes separation and the other promotes union.

To make sure we don't do stupid things to confuse our buttons and hyperlinks. We will create a CSS bookmark using a smart attribute selector and test the validity and quality of each of the two elements.

Inspired by a bit of Eric Meyer's article and some clues from DiagnostiCSS, this stylesheet will combine attribute selectors and: not selectors (or non-pseudo-classes) to highlight problems in HTML. Unlike the other two implementations, it uses pseudo-elements to print errors to the screen. Each error is displayed with a comic font and a pink background.

By linking functions with forms, we can see that ugly HTML can indirectly lead to ugly CSS. This is the consequence of the designer's misuse of the document. Try saving reveng.css to your CSS bookmarks and click on the bookmark to trigger it on any page you like. Note: It will not work in pages where the service is on the https protocol.

REVENGE.CSS
Drag to your bookmarks bar.
Rule 1

 
If it's a hyperlink, it should have the href attribute.

 
a: not ([href]): after
{content:
"Do you mean for this to be a link or a button, because it does not link to anything!";
display: block! important;
background: pink! important;
padding:
0.5em! Important;
font-family:
"comic sans ms", cursive! important;
color:
# 000
! important;
font-size:
16px! Important;
}
Hell
Note: In this example, I am not testing the value of the attribute, but to test whether the attribute is set, that is, [href] matches any element that contains the href attribute. This test only works for hyperlinks. This test can be understood as, "For each element that does not have the href attribute, add a dummy element to it and report an error message in the dummy element."

Rule 2

 
"If the hyperlink has an href attribute, then this attribute should have a value."

 
a [href = ""]: after, a [href $ = "#"]: after, a [href ^ = "javascript"]: after {content:
"Do you mean for this link to be a button, because it does not go anywhere!";
/ * ... ugly styles ... * /
}
Hell
Note: If the value of the href attribute is empty or ends with # or is using Javascript, then it should be used as a button implemented by a non- <button> tag. Note that I am using "start with javascript" to avoid using values like javascript: void (0). But we also cannot expect it to always be written this way.

Rule 3

 
"If it uses the button class, it should be a button, at least on the accessibility layer."

 
.button: not (button): not ([role = "button"]): not ([type = "button"]): not ([type = "submit"]): not ([type = "reset"] ): after, .btn: not (button): not ([role = "button"]): not ([type = "button"]): not ([type = "submit"]): not ([type = "reset"]): after, a [class * = "button"]: not ([role = "button"]): after
{content:
"If you are going to make it look like a button, make it a button, damn it!";
/ * ... ugly styles ... * /
}
Hell
Note: In this example, we show you how you can use chained negation when testing property values. Each selector can be understood like this: "If an element has a class indicating that it is a button, but it is not a button element, and there is no correct role value to make it a button in the accessibility layer, and It's also not a button type input element, okay ... you're lying. "I had to use [class * =" button "] to capture the hyperlinks in Topcoat that didn't use a role to become the actual button. Different classes (up to 62!). I noticed that some developers use button-container and other similar class names on the parent element of the button, which is why the a modifier is included. You can notice that the .btn class is used in Twitter Bootstrap, (if you read its component documentation carefully) you will know that it is not possible to determine whether to use a link or a button as a button.

Rule 4

 
If an element has role = "button", it should be able to link to somewhere even without Javascript.

 
a [role = "button"]: not ([href * = "/"]): not ([href * = "."]): not ([href * = "?"]): after
{content:
"Either use a link fallback, or just use a button element.";
/ * ... ugly styles ... * /
}
Hell
Note: We can fairly determine that the href that does not contain /,. (Usually before the file extension) or? (The beginning of the query string) should be false. It is nice to make the link behave like a button and when javascript is enabled and return: false. The reason is that when javascript is closed it can also link to somewhere. In fact, this is just a reasonable reason I can think of not using <button>.

Rule 5

 
"You cannot disable a hyperlink."

 
a.button [class * = "disabled"]: after, a.btn.disabled: after, a [class * = "button"] [class * = "disabled"]: after
{content:
"You cannot disable a hyperlink. Use a button element with disabled =" disabled ".";
/ * ... ugly styles ... * /
}
Hell
Note: Even the very old user agents can recognize the disabled attribute, so we can use it appropriately in some suitable elements. The example above shows that you can concatenate attribute selectors as if you were concatenating multiple classes: In the last three selectors, we declare, "If a hyperlinked class contains a button string and a disabled string , It will print an error message for it. "Twitter Bootstrap uses the second form, .btn.disabled, in its style sheet, but does not include the a prefix. If it was used in a hyperlink, we would just consider it an error.

Rule 6

 
"The buttons in the form should have a clear type."

 
form
button: not ([type]): after
{content:
"Is this a submit button, a reset button or what? Use type =" submit ", type =" reset "or type =" button "";
}
Hell
Note: We need to determine if the buttons in the form have an explicit type, as some browsers set all button elements that have no explicit type to type = "submit". If the button in our form has another parent, we must absolutely guarantee that the type of the button is not submit.

Rule 7

 
"Either a button or a hyperlink should have something in it or have an ARIA label."

 
a: empty: not ([aria-label]): not ([aria-labelledby]): after, button: empty: not ([aria-label]): not ([aria-labelledby]): after, button: not ([aria-label]): not ([aria-labelledby]) img: only-child: not ([alt]): after, a: not ([aria-label]): not ([aria-labelledby] ) img: only-child: not ([alt]): after
{content:
"All buttons and links should have text content, an image with alt text or an ARIA label";
/ * ... ugly styles ... * /
}
Hell
Note: Buttons and links have no clear purpose-in the form of text and images-and are fairly fake. The last two selectors are the most complicated selectors I have written. For the hyperlinked version, this selector should be understood as "If a hyperlink does not have the aria-label attribute or aria-labelledby attribute, and it contains only one picture element as content, but the picture does not have the alt attribute , Then the relevant error message will be printed. "Also, pay attention to this": empty selector ". The argument is that those elements that are not automatically closed should never be left empty.

to sum up
The selectors and patterns I used to describe in the examples above are not meant to try something different and write something. Property selectors are also nothing new. IE 6 is the only browser that does not support it. The reason I use them is because I don't have the time and energy to write selectors over CSS and write them all over in HTML. I use [role = "banner"] instead of .page-header in the head of my page because this is the only way I know-based on seeing the expected visual effects-and being able to place navigation signs In the right place.

There is no so-called semantic CSS, only the semantic HTML and its visible form. In this article I have shown these things. By directly combining the functions and composition of web pages, you can establish reward and punishment mechanisms. On the one hand, you can set the selector to add visible patterns to those tags that are used correctly; on the other hand, you can find the ugly wrong way to apply the tag structure and print them on the page for errors.

Honestly, not all style hooks are completely semantic and intelligent. Classes are described as padding for elements that need to be applied and attributes that have not yet become standard. So you can see that .footer becomes <footer> and type = "text" (to verify the url through javascript) becomes that you can directly use type = "url" to verify the url. Other times, it is very useful when doing non-semantic layout based on grid framework scaffolding.

However, when you decide to give your CSS completely independent logic, there must be unnecessary disputes between features and structure. In this case, you must raise your vigilance so that they will not be difficult to understand and lose effect. To make matters worse, the pursuit of writing fully semantic classes tends to get you into endless discussions about what a semantic class is. You will start to operate the TV with the remote control in less time and spend more time standing in front of you, thinking about how to use your remote control.

Life is short, please cherish time.

Translator Sign Language: The entire translation is carried out according to the original line, and a little personal understanding of the technology has been added during the translation process. If there is something wrong with the translation, I would like to ask colleagues to give pointers. Thank you!

If you need to reprint, please indicate the source:

English original text: http://coding.smashingmagazine.com/2013/08/20/semantic-css-with-intelligent-selectors/

Chinese translation: http://www.w3cplus.com/css/semantic-css-with-intelligent-selectors.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.