Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select an element only when inside another element?

I have a question regarding CSS selectors. How do I select a <div> with a specific class name only when its inside a <ul> with a class name saft? This CSS class is used elsewhere and I don't want to change the styling everywhere.

<div id="floater">     <ul class="saft">         <li><div class="textSlide"></li>     </ul> </div> 
like image 324
RonanC Avatar asked Aug 08 '12 11:08

RonanC


People also ask

How do I select a tag within another tag in CSS?

The element element selector is used to select elements inside elements.

How do I target a specific element in CSS?

URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element. The :target selector can be used to style the current active target element.

How do I select a tag within a div?

We can use document. querySelector on to select a div and then select an element within it with the given class after that. We just call querySelector on the element with the ID mydiv to select items inside that div.

How do I access nested elements in CSS?

CSS Selector - How to use CSS nested element Selector The element element is called nest selector or Descendant Selector. It selects elements inside elements. We can use Descendant Selector to select an element based on its status as a descendant of another element.


2 Answers

Simply use the CSS descendant selector (a space) between the parent element and the descendant element:

ul.saft div.textSlide {     /* CSS rules */ } 

JS Fiddle demo.

In this case the rules applied to the div of class textSlide will only apply if its ancestor is a ul of the class saft. You could, instead, use the immediate child combinator, the > but then you'd have to specify the div in relation to each parent/ancestor up to the one whose class is required, which gives potentially difficult to maintain CSS (not in this case, but it can, over time, become problematic).

like image 119
David Thomas Avatar answered Oct 07 '22 16:10

David Thomas


Just do:

ul.saft .textSlide {

This achieves what you need

like image 27
Andy Avatar answered Oct 07 '22 14:10

Andy