Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use CSS to select an element only if a specific element comes after the one you want to select?

Using CSS and the following example, is there a way to select only <p>'s that are followed by <ul>'s?

If not, what is the jQuery selector, or would it require an if statement?

<p>Hello there.</p>

<p>Select this para!</p>
<ul>
    <li>list item</li>
</ul>

<ul>
    <li>don't select this list! :)</li>
</ul>

<p>And don't select this paragraph! :)</p>
like image 971
jonathanbell Avatar asked Jan 22 '13 23:01

jonathanbell


People also ask

How do you select an element after an element in CSS?

If you want to select an element immediately after another element you use the + selector.

How do I select a specific element in CSS?

The CSS id Selector The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Which CSS type do you use to apply the style only to a specific element?

Inline CSS is used to style a specific HTML element. For this CSS style, you'll only need to add the style attribute to each HTML tag, without using selectors. This CSS type is not really recommended, as each HTML tag needs to be styled individually.

Is it possible to make a class selector for a particular element if so how?

You can create a selector that will target specific elements with the class applied.


2 Answers

It's not possible in CSS3, the best you can do is select only the <ul> which follow <p>:

p + ul { /*...*/ }

However it will be possible when browsers start implementing the CSS4 subject operator:

!p + ul { /*...*/ }

In the meantime, you'll have to use jQuery and walk the DOM back.

like image 102
robertc Avatar answered Oct 13 '22 18:10

robertc


Unfortunately, you are going to need to turn to javascript. The closest CSS selector to what you want (adjacent sibling selector) would do the exact opposite of what you want. For example, you could select all <ul> after a <p> like this:

p + ul { //style }

You can however make this selection in jQuery like this:

$('p + ul').prev('p')

So you first select all <ul> immediately after <p> and then select the previous <p> from them.

like image 36
Mike Brant Avatar answered Oct 13 '22 20:10

Mike Brant