I have a php code that display all categories of my store, the only problem with this code is give me this structure: ul > li > ul > li. I want to be able to change in css for example the Parent Category to have the color red and Child Category to have the color blue.
I try to use something like:
.sidebar.sidebar-additional ul li:first-child {color: red;}
but is not okay, both texts Parent Category and Child Category have the same red color.
What I can do be able to select both texts separately?
function categoryLoop($id){
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$categories = $objectManager->create('MagentoCatalogModelCategory')->load($id);
if($categories->hasChildren()){
echo '<ul>';
$subcategories = explode(',', $categories->getChildren());
foreach ($subcategories as $category) {
$subcategory = $objectManager->create('MagentoCatalogModelCategory')->load($category);
echo '<li>';
echo $subcategory->getName();
echo "</li>";
if($subcategory->hasChildren()){ categoryLoop($category); }
}
echo "</ul>";
}
}
The html output is:
<ul>
<li>Parent Category</li>
<ul>
<li>Child Category 1</li>
<li>Child Category 2</li>
<li>Child Category 3</li>
</ul>
</li>
</ul>
Thank you
3
Answers
You can set all
li
to red, and then target theli
you want to be blue, by specifically selecting those that are nested within twoul
you can use the direct child selector
ul > li
which selects only the direct child and not the lower childsAlternatively:
}
CSS
There are two ways to get this done:
1. CSS
Style the parent as red and the children to blue.
2. PHP
Output the parent with some predefined class, and children also with a different class:
Then with CSS:
The code you provided should change like this:
And then: