Do all HTML elements support any CSS rule and are they all capable of being inherited?

Are there any restrictions on applying specific CSS rules to certain HTML elements, or can any valid rule be used on any element?

  1. Is it legal to apply any valid CSS rule to any HTML element?
  2. Can any rule be inherited?
  3. What is the inherited value, particularly when it doesn't make sense for a specific property to be applied from an element?

A scenario I am facing involves developing a button component with modular CSS that may include an SVG element for displaying an icon. I want the ability to style the icons (such as stroke and fill) externally while maintaining encapsulation without using deep selectors.

To address this issue, I made the SVG element inherit stroke and fill properties from the button. By applying these properties to the button, the icon inherits them to achieve the desired outcome!

This approach raised questions on whether it is valid and if other browsers would behave similarly.

While this concept appears straightforward, finding a clear answer has proven challenging. Any pointers to relevant excerpts from the specifications or support tables would be greatly appreciated!


I cannot provide a 100% accurate example due to my coding style, but essentially, I am seeking confirmation on the validity of the following:

.icon {
  stroke: inherit;
  fill: inherit;
}

.button {
  stroke: #FFF;
  fill: #999;
}
<button class="button">
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18">
    <g stroke-width="2" transform="translate(1 1)">
      <path d="M14 2L2 14"/>
      <circle cx="8" cy="8" r="8"/>
    </g>
  </svg>
  <span>My button</span>
</button>

Answer №1

Is it permissible to apply any valid CSS rule to any HTML element?

Absolutely, however, your browser may choose to ignore it if the rule is not supported or applicable to that specific element.

Additionally, can any rule be inherited?

Indeed, but it's important to understand that inheritance takes into account the computed value which can produce variations:

The use of the inherit CSS keyword results in the element inheriting the computed value of the property from its parent element. This can be used for any CSS property, including the shorthand all. ref

I don't have a direct example related to SVG at hand, however, here's another illustration:

.box {
  display:inline-block;
  float:left;
  width:200px;
  height:200px;
  border:1px solid red;
}

.box > div {
  display:inherit;
  border:1px solid green;
}
<div class="box">
  <div>text</div>
</div>

Notice how the inner div will exhibit a display of block and not inline-block because float necessitates the computed value of display to be block for .box

To circumvent potential issues with inheritance, consider utilizing CSS variables for your situation:

.icon {
  stroke: var(--s);
  fill: var(--f);
}

.button {
  --s: #FFF;
  --f: #999;
}
<button class="button">
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 18 18">
    <g stroke-width="2" transform="translate(1 1)">
      <path d="M14 2L2 14"/>
      <circle cx="8" cy="8" r="8"/>
    </g>
  </svg>
  <span>My button</span>
</button>

Answer №2

Temani provided a very insightful answer that guided me in the right direction. After conducting some research, I am now confident in creating a more detailed and properly referenced response to my initial query.

Is it permissible to apply any valid CSS rule to any HTML element?

Absolutely. The CSS2.1 specification clearly states this fact: https://www.w3.org/TR/CSS2/about.html#applies-to (CSS3 being an extension of CSS2.1 continues to uphold this principle). It explicitly mentions:

All elements are considered to have all properties, although some properties may not affect certain types of elements aesthetically. For instance, the 'clear' property exclusively impacts block-level elements.

The statement All elements are considered to have all properties implies the freedom to set any property on any element.

The phrase Some properties have no rendering effect on some elements indicates that particular elements may simply overlook specific properties when displaying content (not necessarily rejecting inheritance).

Can any rule be inherited?

To address this question, let's refer to the CSS Values and Units Module Level 3 specification: https://www.w3.org/TR/css3-values/#common-keywords. According to this document:

All CSS properties can accept the CSS-wide keyword values as their sole property value component.

The essence of this statement is that any property has the ability to utilize inherit as its value, affirming a resounding yes to the inquiry. However, the crucial aspect lies in how the inherited value is determined, as previously highlighted by Temani.

How are inherited values calculated?

For an in-depth understanding of cascading and inheritance, one should delve into the CSS Cascading and Inheritance Level 3 specification: https://www.w3.org/TR/css-cascade-3/. This documentation articulates:

The inherited value of a property on an element corresponds to the computed value of the same property on the element’s parent.

Based on this guideline, here's a simplified outline of the process for determining the computed value of any property on any element:

  1. Gather all declared values for a property on an element - encompassing pertinent and valid CSS declarations from developer style sheets, user agent style sheets, etc.

  2. Evaluate the cascaded value - the prevailing value among all declared values (where rules are prioritized to determine a single victor).

  3. If there is no cascaded value, resort to the inherited value for inheritable properties.

  4. If the property isn't inherently inherited, default to the initial value. Each property adheres to an initial value per the specification (e.g., the initial font-size is medium; noteworthy that it's relative rather than absolute like 16px!).

  5. At this stage, a property will possess a distinct value, even if it's relative, contingent upon other CSS properties (e.g., a percentage value hinges on an absolute value such as the parent's dimensions). Efforts are made to resolve the value to ensure clarity and readiness for inheritance.

    It's essential to underline that akin to stipulating an initial value for each property, the specification also defines the procedure for deriving the computed value. MDN, for instance, outlines the computed value for font-size:

as stated, with relative lengths converted to absolute lengths

Thus, while medium remains unchanged, 1.2em transforms into something like 19.2px (considering the parent's font size is 16px).

The crux of the matter

The Cascading and Inheritance specification underscores that:

The computed value persists irrespective of whether the property applies (per the “Applies To” line). Nonetheless, some properties might alter their computation method based on applicability to the element in question.

Hence, every element boasts a computed value for every property, though not necessarily employing it (the used value, next in line after computed value, could be absent). Nevertheless, the computed value serves as the basis for inheritance.

In context of my SVG button demonstration:

  1. I unquestionably hold the authority to define stroke and fill attributes for a <button>. While these attributes won't impact the button directly, they'll get transmitted to child elements as necessary.
  2. The subsequent SVG child elements will inherently acquire these attributes without explicit declaration.
  3. The computed values for stroke and fill lack constraints, ensuring proper color inheritance (successfully validated!).

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

Attempting to retrieve the list of 'Style' for a GtkWidget

Seeking assistance in obtaining a list of style properties for a GtkWidget (GtkButton). Here is the current code I have: #include <gtk/gtk.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main (int argc, char *argv ...

Utilizing CSS for styling a class with a dynamic name

On the server side, I am dynamically generating class names like this: <p class="level_1">List item 1</p> <p class="level_2">List item 2</p> <p class="level_3">List item 3</p> <p class="level_1">List item 1</p& ...

Filling HTML5 Datepicker Using Information from a Model

Currently, I am in the process of developing a basic scheduling application for a project. To simplify the task of selecting start and end times/dates for our events, we have included a simple DateTime picker in the source code: <input type="datetime-l ...

How can I display the secondary menu in Wordpress on specific pages only?

I recently set up a secondary menu in my WordPress theme by adding it to the function.php file. However, now both the primary and secondary menus are showing on every page, giving me double menu bars on the top of my home page and about us page. I only wan ...

The grayscale effect is not functioning on the default web browser of an Android device

I have implemented a grayscale effect for an image using the following CSS code snippet: img.grayscale { filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\&apo ...

Discover the new SASS color theme in Bootstrap 5.3 with the addition of Subtle and Emphasis classes for

I'm in the process of enhancing my Bootstrap SASS theme with a new color scheme. I have a customized file that includes modifications and introduces a new color: GOLD. After conducting extensive research and reading various resources, I successfully ...

What is the method to achieve this layout shown in the image using CSS grid?

.grid-container { display: grid; grid-gap: 10px; grid-template-columns: 2fr 1fr; grid-template-rows: 1fr 1fr; } .grid-item { background: blue; height: 100px; } .grid-item .item1 { grid-row-start: 1; grid-row-end: 3; } <div class="grid- ...

Checking the size of input fields prior to database storage

In developing an html form to insert input data into a mysql database, I have implemented serverside form validation in java to prevent any issues. One key validation I need to perform is to ensure that the data entered is not too large for the respective ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

What is the process for adjusting the width of an element using JavaScript?

I have a unique bar with one half red and the other green. I am trying to subtract 1vw from the width of the red section. Unfortunately, using style.width is not yielding the desired result. See below for the code snippet I am currently using: //FIGHT do ...

Why isn't the image utilizing all the available space?

I'm working on creating a simple card to display services, with just an image and some text. However, I'm facing an issue where the image is not taking up the full width and height of the container as expected. Could someone help me figure out w ...

Seeking suggestions for an HTML line graph to visually represent the status of devices

Seeking advice on the best chart library for displaying device states (on/off) across a timeline in an HTML page. The graph should resemble a logic analyzer display with each device represented by a separate line on the Y axis, toggling between high and lo ...

Decrease the z-index of the Bootstrap 4 card to be lower than that of the table

I'm struggling with a Table that has a fixed header. The issue is that the card elements keep scrolling on top of the fixed header. I've attempted to adjust the z-index of thead and decrease the z-index of the card element, but nothing seems to b ...

The Angular checked functionality is not working as expected due to the presence of ngModel

Just getting started with Angular here. I’m working on a checkbox table that compares to another table and automatically checks if it exists. The functionality is all good, but as soon as I add ngModel to save the changes, the initial check seems to be ...

The sticky sidebar feature in Bootstrap 4 is not functioning correctly as it scrolls with the page instead of

I'm trying to create a sticky right sidebar titled "Recent Posts in Category" on this page. I want it to stay fixed when the user scrolls down. Since Bootstrap 4 no longer supports the affix feature, I attempted to accomplish this using CSS. I came a ...

Distinguishing between if(a) and if(a!=null && a!=undefined)

While attempting to populate data in the DOM, I am encountering numerous issues due to the absence of values in the objects or arrays I am trying to utilize. Take, for instance, the following object: var obj = { name: 'rajat', age: 20 } Gi ...

How to seamlessly adjust the height from 0 to auto

My goal is to smoothly transition from height: 0; to height: auto; and reveal the content inside a <div></div>. One effective method I've come across involves using the max-height property. Here's an example of how it can be implement ...

During the printing process, Vuetify applications allocate space for hidden elements

I have developed a Vue.JS and Vuetify application inspired by the Google Contacts layout. The design includes both a toolbar and a navigation drawer. My goal is to print the content from the browser without including the toolbar and nav drawer. To achieve ...

Optimize Embedded Videos to Utilize Maximum HTML Element Width

I am facing an issue with embedding a Youtube video inside a td HTML element. I want the video to maintain its aspect ratio while expanding to fit the width of its parent td. My desired look for the video is like this: However, my current video appears l ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...