What allows CSS to interact with pseudo-elements?

While experimenting in my class, I made an interesting discovery that CSS can be applied to custom elements.

For example:

imsocool {
    color:blue;
}
<imsocool>HELLO</imsocool>

Surprisingly, when my professor noticed me using these custom elements, he suggested replacing them with paragraphs styled with ID's. I wonder why he discourages the use of custom elements when they are effective.

It's puzzling why my professor was unaware of the existence and functionality of custom elements in CSS. Could it be that they are not commonly used?

Answer №1

What is the reason behind CSS being compatible with fictitious elements?

Most browsers are designed to be somewhat forward compatible with future HTML additions. Although unrecognized elements are parsed into the DOM, they lack semantics or specialized default rendering.

Occasionally, CSS, JavaScript, and ARIA can be utilized to mimic the functionalities of new elements in older browsers, requiring these elements to be present in the DOM for manipulation by those languages to add the desired functionalities.

(The custom elements specification exists, but they adhere to specific naming guidelines and necessitate registration through JavaScript.)

What is the rationale behind my professor's disapproval of fabricated elements?

  • They go against the rules outlined in the HTML specification
  • They run the risk of causing conflicts with future standard elements sharing the same name
  • In most cases, there already exists an HTML element better suited for the required task

Additionally, why was my professor unaware of the existence and functionality of fictitious elements within CSS? Are they rare?

Indeed, fabricated elements are not commonly used due to the aforementioned issues.

Answer №2

Summary:

  • Using custom tags in HTML is not recommended due to potential rendering issues.
  • Utilizing valid HTML code makes future development easier and offers benefits such as SEO and speed.
  • Valid CSS/HTML is preferred by Google for SEO and can improve website professionalism.

Detailed Explanation:

While some argue that custom tags enhance usability, they can result in invalid HTML, which can negatively impact the site's performance.

Ensuring valid HTML is essential for various reasons, including SEO benefits, cross-browser compatibility, and overall website professionalism.

  • Google favors valid HTML for SEO purposes.
  • Valid HTML improves browser compatibility and usability.
  • Validation helps prevent obscure bugs and improves overall website performance.

Validating HTML code is recommended by W3C for debugging, future-proofing, maintenance ease, teaching good practices, and showcasing professionalism.

Answer №3

YADA (yet another (different) solution)

Note: Take note of the valuable insight shared by BoltClock in the comment below regarding type versus tag versus element. While I usually overlook semantics, his point is quite significant and enlightening.

Despite the existing array of responses, the fact that your professor encouraged you to post this question suggests that you are (officially) enrolled in school. In light of this, I wanted to delve deeper into not only CSS but also the inner workings of web browsers. As stated by Wikipedia, "CSS is a style sheet language used for describing ... a document written in a markup language." (I highlighted "a") It is important to note that it does not specify "written in HTML" nor a particular version of HTML. CSS can be applied to HTML, XHTML, XML, SGML, XAML, etc. Naturally, you require something to display each of these document types while also applying styling. Essentially, CSS does not recognize / comprehend / consider specific markup language tags. Therefore, the tags may be deemed "invalid" in terms of HTML, but there is no such concept of a "valid" tag/element/type in CSS.

Modern web browsers are not homogeneous entities. They consist of various "engines" tasked with specific functions. At a minimum, I can identify 3 engines: the rendering engine, the CSS engine, and the JavaScript engine/VM. I'm uncertain if the parser is part of the rendering engine (or vice versa) or if it operates independently, but you grasp the concept.

Whether a visual browser (others have already discussed the challenges screen readers might encounter with invalid tags) applies the styling hinges on whether the parser retains the "invalid" tag in the document and if the rendering engine actually enforces styles on that tag. For ease of development and maintenance, CSS engines are not programmed to comprehend that "This is an HTML document, so these are the valid tags / elements / types." Instead, CSS engines simply identify tags / elements / types and convey to the rendering engine, "Here are the styles to apply." Ultimately, the rendering engine decides whether to implement the styles or not.

Here's a simple way to conceptualize the basic flow from one engine to another: parser -> CSS -> rendering. While the actual process is more intricate, this serves as a decent starting point.

Given the length of this response, I'll conclude here.

Answer №4

Modern browsers treat unknown elements as divs, thanks to the upcoming HTML5 standard which allows for a modular structure where new elements can be added.

For older browsers like IE7-, a JavaScript trick can be used to make these unknown elements work as well.

Check out this related question I stumbled upon while searching for an example.

And here's a helpful question discussing the JavaScript fix for these elements not being supported in IE7.

One might wonder why the lack of knowledge concerning custom tags and their functionality. Are they not well-known?

Indeed, they are not widely used and do not serve a specific purpose. These custom elements are a newer addition in html5, whereas in previous HTML versions, unknown tags were considered invalid.

It's not uncommon for teachers to have gaps in their knowledge, perhaps due to the demand of teaching the basics and not needing to stay fully updated on every detail. I once received detention for allegedly programming a virus because I made a computer play music using the play command in GWBasic. (True story, from a long time ago). Regardless, the advice to refrain from using custom elements is sound.

Answer №5

You have the ability to utilize custom elements for your projects. The W3C spec offers detailed information on this topic:

http://w3c.github.io/webcomponents/spec/custom/

If you're looking for a tutorial on how to implement custom elements, check out this resource:

http://www.html5rocks.com/en/tutorials/webcomponents/customelements/

It's important to note, as mentioned by @Quentin, that this specification is still in the early stages of development and comes with certain limitations on the names of elements that can be used.

Answer №6

In reviewing the other responses, it appears that some are inadequately worded or may contain inaccuracies.

FALSE(ish): Non-standard HTML elements are not necessarily "not allowed", "illegal", or "invalid".

They are actually "non-conforming". So, while something may not conform, it can still be allowed. The W3C does not enforce strict rules on this matter.

The W3C intentionally allows for flexibility in their specifications to accommodate different community needs. If a specific community requires new elements for their purposes, they can establish "other applicable specifications" with the W3C.

Strict validators may flag non-standard elements as "invalid" based on the specified criteria, but this does not necessarily impact the functionality or legality of the element for browser or user use.

FALSE(ish): Non-standard HTML elements might result in rendering issues

The likelihood of rendering issues due to non-standard elements is low. Any potential problems would typically arise if a custom element conflicts with existing specifications or coding practices.

CSS can style non-standard tags because the HTML specification dictates that unknown elements should be treated neutrally and styled accordingly by CSS processors.

It's important to be aware that changes to the HTML spec in the future could impact styling for custom tags.

Non-standard tags and JavaScript (via the DOM)

Custom elements can be manipulated using JavaScript because the specification outlines how they should be handled within the Document Object Model (DOM).

TL;DR: Striving for conformity with the spec facilitates communication and safety, but non-conformance is still permissible for most purposes.

For instance:

var wee = document.createElement('wee');
console.log(wee.toString()); //[object HTMLUnknownElement]

These insights may invite debate, but they reflect my perspective.

Answer №7

As per the specifications:

Cascading Style Sheets (CSS)

A type selector refers to the name of a document language element type written using CSS qualified names syntax

I initially believed this was referred to as the element selector, but it is, in fact, known as the type selector. The spec elaborates on CSS qualified names, stating that there are no restrictions on the actual names used. Essentially, as long as the type selector adheres to CSS qualified name syntax, it is considered correct CSS and will match the element in the document. This means there are no CSS-specific limitations on elements that do not exist in a specific spec, whether HTML or otherwise.

HyperText Markup Language (HTML)

There are no official constraints on including any tags you desire in the document. However, the documentation does caution

Authors should not use elements, attributes, or attribute values for purposes other than their intended semantic purpose, as this can hinder correct processing of the page by software.

It further states

Authors should avoid using elements, attributes, or attribute values not permitted by this specification or other applicable specifications, as this can complicate future language extensions.

It's unclear whether the spec explicitly states that unknown elements are permitted, but it does mention the HTMLUnknownElement interface for unrecognized elements. Some browsers may not recognize elements even if they are in the current spec (such as IE8).

Although there is a draft for custom elements, it is unlikely to be implemented anywhere at this time.

Answer №8

Utilizing HTML5 to create custom elements is an option, but it's important to consider compatibility with older browsers.

If you opt to use custom tags, be sure to include comments in your HTML code! This can help others understand and troubleshoot the code more easily.

For example, add a comment like this:

<!-- Using custom tags, reference their CSS here -->

Older browsers may not recognize custom tags/elements, similar to how they may not recognize HTML5 elements like nav or section.

If you're interested in this concept, it's recommended to implement it correctly.

Getting started

Custom Elements enable web developers to define new types of HTML elements. This specification is a crucial part of the Web Components framework, allowing developers to:

- Define new HTML/DOM elements - Create elements that inherit from existing elements - Bundle custom functionality into a single tag - Extend the API of current DOM elements

There are numerous possibilities with custom elements, enhancing the appearance of your code as highlighted in this article on Defining New Elements in HTML with Custom Elements.

Summing it up:

Pros

  • Offers a refined and clear code structure.

  • Reduces the need for excessive divs. :p

  • Provides a distinct touch to the codebase.

Cons

  • Consideration must be given to compatibility with older browsers.

  • Other developers may require guidance on using custom tags (provide explanations or comments).

  • Custom tags may necessitate more CSS due to lack of default styling.

The decision to use custom elements is up to individual discretion and should align with the project's requirements.

Update 1/2/2014

Sharing a helpful article I came across on Custom Elements.

Understanding the tech behind Custom Elements - Custom Elements empower authors to define their own elements. By associating JavaScript code with custom tag names, authors can seamlessly integrate these custom elements like standard tags.

For instance, after defining a special button as super-button, it can be utilized like any standard button:

Custom elements are essentially elements. They can be created, utilized, modified, and combined just as easily as standard elements today.

While this library seems promising, it's worth noting that it may not have passed Window's Build status and is currently in a pre-alpha stage, so it's advisable to monitor its progress.

Answer №9

What is the reason for his reluctance to utilize them? These elements are not widely used and are not included in the official HTML5 standard. In essence, they are considered a workaround.

Personally, I am fond of these elements. You might want to explore XHTML5, which allows for the creation of custom tags that can be used within the standard.

Additionally, as others have noted, these elements are non-compliant and therefore may not work consistently across different platforms.

Why was he unaware of their existence? It's possible that they are simply uncommon, leading to a lack of awareness. Perhaps he didn't realize they could be used at all.

Answer №10

Utilizing fabricated tags is seldom practiced, as they may not function consistently across all current and future browsers.

Browsers must interpret HTML code into familiar elements, thus fabricated tags will be transformed into something else to conform to the document object model (DOM). Since web standards do not encompass how to handle everything outside of the standards, browsers tend to handle non-standard code in varied manners.

Web development is already complex with diverse browsers having their unique behaviors, adding another level of uncertainty is not ideal. It is advisable to adhere to standards-compliant practices as that is what browser vendors aim to uphold, ensuring a higher chance of functionality.

Answer №11

In my opinion, fabricated tags can create additional confusion and lack clarity compared to paragraphs with IDs (usually associated with a specific block of text). It is commonly understood that a paragraph with an ID serves as a designated block of text, whereas the purpose of made-up tags may not be as easily discernible. This is more of a matter of style and clarity rather than functionality.

Answer №12

While previous responses have been insightful, it is important to highlight the significance of custom elements and attributes within frameworks like AngularJS. These elements not only enhance the semantic value of the XML, but also contribute to the functionality, appearance, and overall user experience of the website.

Answer №13

Cascading Style Sheets (CSS) is a powerful language used to style not only (X)HTML documents, but also XML documents. Your snippet containing fictional tags could potentially be a valid XML document if enclosed within a single root element. Have you wrapped it with an <html> ...</html> tag? Any modern browser is capable of rendering XML documents.

However, this makeshift XML lacks a proper grammar and XML declaration. If you were to use an HTML declaration header instead (along with ensuring the server sends the correct mime type), it would be considered invalid HTML.

(X)HTML offers advantages over plain XML due to the semantic meaning associated with its elements, which is crucial for web page presentation. This semantic structure allows for easier collaboration among developers, reduces errors, and enhances readability.

In certain scenarios, utilizing CSS with XML and/or XSLT for presentation is more practical. While this may have been your approach, given that HTML/CSS is typically the preferred method, it's recommended to stick with it in your specific situation.

Remember to include an (X)HTML header in your document to ensure that tools can provide you with meaningful error messages.

Answer №14

...I prefer to convert all of my custom tags into paragraphs with unique IDs.

I have a different perspective on the proper way to handle this issue.

  1. A <p> tag is specifically for paragraphs. It's common to see people using it instead of a div for spacing or aesthetics. If it's not a paragraph, it's best to avoid using it.

  2. It's unnecessary to assign IDs to everything unless you need to specifically target it (e.g., with Javascript). Using classes or a standard div is usually sufficient.

Answer №15

Since its inception, CSS has always been designed to be independent of any specific markup language, allowing it to be utilized with any markup language that generates tree-like DOM structures (such as SVG). Any tag that conforms to the "name token" production is considered valid in CSS. Therefore, the focus of your question should be more on HTML rather than CSS itself.

The HTML5 specification supports elements with custom tags. HTML5 outlines how unknown elements should be interpreted in the DOM, making it the first HTML specification to officially enable custom elements. To make use of custom elements, you simply need to include the HTML5 doctype <!DOCTYPE html> in your document.

Regarding the custom tag names...

This document from W3C suggests that custom tags should include at least one "-" (dash) symbol to prevent potential conflicts with future HTML elements. It is recommended to modify your document as follows:

<style>
so-cool {
    color: blue;
}
</style>

<body>
    <so-cool>HELLO</so-cool>
</body>

Answer №16

It is surprising that accessibility was not mentioned by anyone, including my past self. Using valid tags instead of custom ones is important for compatibility with various software, including screen-readers and other tools needed for accessibility. Laws like WAI mandate that websites be accessible, which often means using valid markup.


Since it wasn't brought up, I'll address it.

This issue stems from the "browser wars."

In the 1990s, as the Internet gained popularity, competition between browsers increased. Some browsers, like Internet Explorer, tried to interpret page design in a way that allowed for incorrect markup to render properly (e.g.,

<b><i>foobar</b></i>
displaying as bold-italics).

This approach made sense to some extent, as users would naturally prefer a browser that rendered pages correctly rather than one that constantly flagged syntax errors. The browser wars seemed to have ended, only to resurface in recent years with the release of Chrome, the resurgence of Safari, and the decline of IE. This "cold war"-like competition among browser vendors has led to browsers deviating from strict web standards in an attempt to gain an edge.

Unfortunately, this leniency has resulted in a proliferation of poorly marked up webpages. Internet Explorer's popularity and tolerance for non-standard code, combined with Microsoft's disregard for web standards, contributed to the propagation of broken and poorly designed pages.

While you may get away with using workarounds on some browsers for now, it is advisable to adhere to web standards when creating web content to ensure compatibility across platforms and avoid issues with future browser updates.

Answer №17

Even though browsers may interpret CSS in relation to HTML tags regardless of their validity, it is imperative that you refrain from using fake tags.

While there may not be any technical issues with this practice in terms of CSS, incorporating fictitious tags in HTML is a big no-no.

HTML functions as a markup language, where each tag is designated for a specific type of content. Your custom tags do not align with any standard type of content, leading to potential complications with web crawlers like Google.

To delve deeper into the significance of accurate markup, check out this resource on the importance of correct markup.

Edit

Divs are utilized for grouping multiple related elements that are meant to be displayed as blocks and manipulated accordingly.

On the flip side, spans are used for elements that require distinct styling within their current context, meant to be displayed inline rather than in a block format. For instance, if specific words in a sentence need to be in all caps.

Since custom tags lack standard correlation, it is recommended to utilize span or div with class/ID properties instead.

There are some very specific exceptions to this rule, such as Angular JS .

Answer №18

Even though CSS includes a feature known as a "tag selector," it does not have knowledge of what a tag actually represents. This determination is left to the language of the document. CSS was created to be compatible not only with HTML, but also with XML, where the tags can vary widely without a DTD or validation scheme. It could potentially be used with other languages as well, but it would require establishing unique semantics for concepts like "tags" and "attributes."

Web browsers typically apply CSS to unfamiliar tags in HTML, as opposed to completely breaking down and failing to display anything. However, it is considered extremely poor practice to intentionally use "fake" tags. This is due to the fact that new tags are periodically introduced, and if one is defined that resembles your fake tag but functions differently, it could lead to issues with your website on newer browsers.

Answer №19

What is the reason for CSS compatibility with pseudo elements? CSS works with pseudo elements without causing harm because they are not intended for regular use.

Why does my instructor discourage the use of fabricated elements? The concern is that if these elements are formally defined in the future, they may behave unexpectedly in your styling.

Furthermore, why was he unaware of the existence and utilization of pseudo elements in CSS? Are they not commonly used? The instructor, like many web developers, recognizes the importance of avoiding elements that could potentially cause issues or inaccuracies in future updates.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Minimize the gaps between items within a CSS grid design

I'm struggling with adjusting the whitespace between 'Job Role' and 'Company Name' in my grid layout. Here's a snippet of what I have: https://i.sstatic.net/l55oW.png The container css is set up like this: .experience-child ...

Textview is cluttering space with Html.fromhtml that is not needed

Situation 1 Here is the code I used to display HTML-formatted text in a TextView. However, it seems to be reserving space for a link that isn't visible. holder.textView.setMovementMethod(LinkMovementMethod.getInstance()); holder.textView.setText(Htm ...

Unable to trigger jQuery onclick event on nested div elements

I'm experiencing an issue with my web-page where two buttons at the top are not responding to a sorting function on the nested #byFilter. Despite trying to apply the onclick(function()) method, it doesn't seem to work. Javascript $(document).re ...

Creating a form with an input field and an image side by side in HTML

I've been attempting to display an HTML input element and an SVG image on the same line without success. I've tried various solutions from stackoverflow, but none seem to work for me. Here's my current HTML code: <div id = "inline_eleme ...

Adjusting the input label to be aligned inside the input box and positioned to the right side

I am currently working on aligning my input label inside the input box and positioning it to float right. The input boxes I am using have been extended from b4. Currently, this is how it appears (see arrow for desired alignment): https://i.stack.imgur.co ...

Issue with Bootsrap 4 Dropdown Menu Displaying Incomplete Links

There seems to be an issue with the Bootstrap 4 dropdown menu not displaying all the links. Please refer to the image below: https://i.sstatic.net/ZS2t2.png The dropdown menu is not showing beyond the red band. I can't seem to figure out what I&apos ...

Utilizing the Bootstrap grid system to seamlessly display images

I have been attempting to design a column that is divided into two nested columns, each containing images that should fill the entire height and width of their respective columns. However, I am facing an issue where the images are extending beyond the boun ...

Converting an HTML page into a JSON object by scraping it

Is there a way to convert an HTML page into a JSON object using web scraping? Here is the content of the page: <html><head><title>Index</title><meta charset="UTF-8"></head><body><div><p>[ <a href ...

What is the reason border-box does not function properly on inline-block elements?

Demo: http://jsfiddle.net/L5jchnpm/ I've encountered an issue where I believed that using display: inline-block would make elements act as both inline and block elements. Additionally, I thought that setting box-sizing: border-box would adjust the w ...

I'm struggling to resolve this error. Can someone please help me figure it out?

` package Xcel; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Workbook; import org.apac ...

Upon clicking on a different div, a div will elegantly slide down from above the footer

I'm struggling with sliding a div from the bottom of the page. Here is my JSFIDDLE Currently, when I click on the blue box (arrow-hover), the div slides up (box-main). However, to hide the div (box-main) again, I have to click inside the box-main d ...

Is there a way to condense a paragraph of text without using a span or div element?

There is a common scenario where I often encounter this issue: <span> <p>hello world</p> </span> It involves reducing the width of a paragraph to fit the text, but unfortunately it leads to clutter in my HTML. Is there a way to ...

Varied selection menu feature

Looking to build a new component: The idea is to create something similar to a dropdown list. I aim to incorporate this component into every cell (td) of table rows. The challenge lies in displaying the second div (item list) under the first div, but abov ...

Why use @media (max-width:-1) in your code?

While reviewing CSS code created by another department, I noticed an interesting media descriptor: @media (max-width:-1) { ...standard css stuff here } The value of max-width cannot be less than 0, so what could be the purpose of this? Perhaps it was ...

Dealing with unsupported CSS properties in Next.js or implementing @supports directives in Chakra-UI

Currently, I am working on a React component that adjusts opacity values based on the support for the CSS backdrop-filter directive: background={(() => { const opacity = isBackdropFilterSupported() ? 0.75 : 0.98 return ( `linear-gradient( ...

Rotate Text in HTML <thead> Tag

I need assistance with rotating a table header. https://i.stack.imgur.com/hcvxx.png The HTML th elements within the thead section are described as follows: <th> <span class="rotate-all">Period</span> </th> <th> < ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

Showing Stationary Pictures at Full Size in OpenLayers

I am trying to showcase static images as maps using a StaticImage layer in ol3, with the image size set at 100% in pixels. However, I am facing difficulty in ensuring that the displayed images are always the correct size based on the extent and zoom variab ...

perform an action in PHP when a button is clicked

I'm currently developing a PHP admin panel that displays a list of users in an HTML table format. Each row in the table includes a button that allows the admin to send a notification to the selected user. Below is the code I used to create and displa ...

In the production and development environments, the interpretation of CSS classnames is being rearranged

Currently utilizing create-react-app v2. I've encountered an issue with a component that has multiple classnames: "x15 x14 login-form__field". Strangely, in the production build, the order of '.x14' and 'login-form__field' seems t ...