Understanding how CSS is inherited in list items (li), unordered lists (ul), and ordered lists (ol)

While experimenting with styling in nested lists using HTML and CSS, I wanted to demonstrate the difference between the child selector (ul > li) and the general descendant selector (ul li). However, when I applied the color red to ul > li, all text in the ul ended up inheriting that color. Can someone please explain why this happens with only text properties like color, text-align, and text-decoration? Meanwhile, properties like background-color and border do not get passed down to grandchildren as they should with the child selector. Or feel free to direct me to a resource where this is explained!

Thanks in advance!

ul {
  background-color: red;
}

ul li {
  background-color: green;
}

ul>li {
  background-color: blue;
  color: red;
  text-align: center;
}

ul>li>ol {
  background-color: pink;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Test</title>
  <link href="styles.css" rel="stylesheet" />
  <link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet" />
</head>

<body>
  <div>
    <ul>
      Unsorted List
      <li>
        First Items In Unordered List
        <ol>
          First Ordered List
          <li>First Ordered Item</li>
          <li>Second Ordered Item</li>
          <li>Third Ordered Item</li>
        </ol>
      </li>
      <li>
        Second Item In Unordered List
        <ol>
          Second Ordered List
          <li>First Ordered Item</li>
          <li>Second Ordered Item</li>
          <li>Third Ordered Item</li>
        </ol>
      </li>
      <li>
        Third Item In Unordered List
        <ol>
          Third Ordered List
          <li>First Ordered Item</li>
          <li>Second Ordered Item</li>
          <li>Third Ordered Item</li>
        </ol>
      </li>
    </ul>
  </div>
</body>
<script src="script.js"></script>

</html>

Answer №1

When properties are assigned the value inherit, they are inherited.

Browsers' default stylesheets typically use inherit as the default value for properties that are generally considered useful to inherit.

For example, it is beneficial that in the following scenario:

<p style="color: blue">The quick <em>brown</em> fox jumped over the lazy dog.</p>

...the em element inherits the color without needing to be redefined.

However, inheriting a background may not be ideal, as it could layer on top of an existing one. A background image would start anew with the em element, while a semi-transparent background color would compound the opacity of its parent.

Answer №2

Let's break down your query into two parts,

  1. What does ul > li mean?

When it comes to the CSS color property, it doesn't just apply to the direct children of ul, but also to elements and their properties within those children unless you specify a different color for them. For example-

<style>
  ul > li {
    color: red;
  }
</style>

<ul>
  <li>HOME</li>
  <li> MY ROOMS
    <ul>
      <li>BED ROOM</li>
      <li>KITCHEN</li>
    </ul>
  </li>
  <li>GARDEN</li>
</ul>

The color: red; is not only applied to ul > li, but also to ul > li > ul > li. If you set a different color for these nested items, they will no longer inherit the color from ul > li, as shown in the example below-

<style>
ul > li {
color: red;
}
  ul > li li {
    color: green;
    border-width: 1px;
    border-style: solid;
  }
</style>

<ul>
  <li>HOME</li>
  <li> MY ROOMS
    <ul>
      <li>BED ROOM</li>
      <li>KITCHEN</li>
    </ul>
  </li>
  <li>GARDEN</li>
</ul>

As you can see, the color of the child list items has changed. You can also notice the borders around them and their colors, addressing the second part of your question-

  1. Does the CSS color property only apply to text?

The answer is NO. When the CSS color property is applied to an element, it also affects other properties of its children, such as:

  • The text color specified by the value of the alt attribute (if it's a child img tag)
  • The border-color of ul, ol, and li (all children of that same element)
  • The color of the list-style-type for li elements (children of that element)

Take a look at this example below-

<style>
  div {
    width: 400px;
    margin: 20px auto;

    /* color */
    color: green
  }

  ol li,
  ul {
    border-width: 1px;
    border-style: solid;
  }
</style>

<div>
  <img src="01.jpg" alt="This is a missing img tag">
  <br>
  <br>
  <ul>
    <li>Lorem, ipsum dolor.</li>
  </ul>
  <br>
  <ol>
    <li>Lorem ipsum dolor sit.</li>
  </ol>
</div>

I came across this information in a tutorial I've forgotten, but after some research, I found an article that might be helpful to you. You can also visit this W3Schools page to learn more about CSS selectors. Good luck!

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

Identify the moment when the SPAN element reappears in sight

I have a question that may have been asked before, but I haven't found a satisfactory answer yet. Within my HTML code, I have a SPAN element with an onclick event, like so: <span onclick='loadDiv()'>Text</span> When a user cli ...

Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python. def func(A): result = 0 ...

Can you create a seamless transition from a horizontal gradient to a vertical gradient in order to conceal something?

I am currently working on achieving a unique effect with three background gradients, including a horizontal mask, top border, and bottom border to seamlessly blend borders into the background: In order to achieve this effect, here is the code snippet I ha ...

"How to ensure a background image fits perfectly on the screen in IE10

I am facing a problem while trying to set the background image in CSS to fit the screen. It works fine with the latest version of Chrome, but there is an issue with IE 10. html { border-top: 10px solid #8A85A5; background: url("http://www.lifeintempe.com/ ...

Using jQuery to alter the background position of multiple backgrounds in CSS

I'm using jQuery to dynamically adjust the background image position of an element based on screen resolution. Here's the code: var pwwidth = $(window).width(); var pwheight = $(window).height(); var bg1posx = pwwidth - $('h1.portofolio&ap ...

Varied spacing between horizontal and vertical items in a list

The issue with the spacing between horizontal and vertical list items is perplexing. Despite having identical margin, padding, height, and width, they seem to display differently. While manual adjustment of margins or paddings can resolve this, I am curiou ...

The Bootstrap 4 container class is known for leaving a peculiar dot next to the container

I am utilizing the container class from Bootstrap 4 to arrange my project details based on screen resolution sizes. However, I have encountered a strange dot that remains even after trying to remove it. You can view the HTML code I am currently working o ...

Choose a navigation item from the list containing a nested span element

I've implemented selectnav from GitHub and it's functioning perfectly. However, my menu consists of list items with a description span inside each one, resulting in menu items structured as shown below: <li><a href="somelink.html">Ch ...

Stylish CSS selector

Is there a way to target CSS path based on the style of an element? For instance, if I have two ul elements on a page - one with a style of list-style-type: lower-alpha;: <ul start="1" style="list-style-type: lower-alpha;"> and the other ul without ...

Ways to display or hide particular div in a table

Coding Example:- '<td>' + item.Message + ' <input type="button" class="btn btn-info" id="' + item.LogID + '" onclick="Clicked(this);" value="View More" /> <p> ' + item.FormattedMessage + ' </p>& ...

The navigation/hamburger icon vanishes after a click on a page link

I'm in the process of creating a single-page scrolling website. However, I am encountering an issue with the navigation bar. Specifically, when I click on a page link from the nav bar at screen widths less than 780px (when the hamburger icon appears), ...

Are there any tools available for converting Arabic HTML to PDF for free?

Converting an HTML page in Arabic to a PDF seems to be a challenge with itextsharp. Below is an example of HTML content with Arabic text: <div> <table border="1" width="500px"> <tr> <td colspan="2"> ...

Creating an angular div with rounded corners in the bottom right corner is a simple and stylish way to enhance the look

I've been attempting to design my div to resemble this example, but unfortunately, I haven't had much luck. I experimented with the polygon method to achieve the desired look, but all I managed to create was an angled line that didn't align ...

Display only distinct dates in the ng-repeat list

I'm trying to display an unordered list created using ng-repeat. Each list item includes a month header and a blog post. I'm struggling to find a clean solution to only show one instance of each month name without resorting to complex jQuery hac ...

What steps can I take to ensure this conversion meets markup validation requirements?

I keep encountering a validation error that keeps coming up: $("#preview").html('<div align="center"><img src="/ajaximage/loader.gif" alt="Uploading...."/></div>'); The error message states: document type does not allow elemen ...

How can I make a dropdown menu appear when I select a checkbox?

Is it possible to have a dropdown menu with changing options appear when I click on a checkbox using HTML and JavaScript? I have experimented with some code snippets in JavaScript as a beginner, but I am unsure if they are needed here. Is there an altern ...

Tips for concealing boostrap spinners

Within the main component, I have an @Input() alkatreszList$!: Observable<any[]>; that gets passed into the child component input as @Input() item: any; using the item object: <div class="container-fluid"> <div class="row ...

Using the glob function within a PHP include statement to search through numerous web directories

Greetings to all readers, this is my first time posting here. I have limited experience with PHP and would appreciate your patience as I navigate through it. I manage a large static website that heavily relies on PHP includes for various sections like hea ...

Is there anyone who can provide a straightforward solution (code) for < something basic?

I have learned a lot about programming, but I'm stuck on one thing. How can I make an image stay in place when clicked on? What I mean is that when you click and hold on the image, then move the cursor, the image moves with the cursor. What I want is ...

Aligning the menu links to the right on a horizontal CSS menu

I have created a horizontal menu using CSS and HTML with the following code: .nav > li:hover { background: #666666; text-decoration:none; } .active { background: #666666; text-decoration:none; } nav, ul, li, a { margin: 0; paddi ...