Is there a way to style only the first element with a specific class? The :first-child psuedo selector seems to only work on tags.
EDIT: Not all classes have the same parent element so :first-child isn't an option.
You may try like this:
<div>
<p class="blue">1st</p>
<div class="blue">2nd</div>
</div>
<div>
<div class="blue">3rd</p>
<div class="blue">4th</div>
</div>
So this will make only the first element as blue
Also check :first-child pseudo-class
The :first-child pseudo-class matches an element that is the first
child element of some other element.
.class-name:nth-of-type(1)
This should style what you want
JsFiddle example
This should work .classNamep:first-of-type
You need to double check your class name. A typo could happen.
See this fiddle. It shows you that :first-child works even with class selectors. :)
Code:
<span class="spana">first</span>
<span class="spana">second</span>
.spana:first-child {
background-color: #ddd;
}
Using the nth-child() pseudo class selector is a good approach, this is supported in all major browsers, including IE9+.
Here is the example HTML:
<div class="blue">Will be blue</div>
<div class="blue">Will not be blue</div>
<div class="blue">Will not be blue</div>
<div class="blue">Will not be blue</div>
And the CSS:
.blue:nth-child(1) {
color: blue;
}
This will select the first div of class name blue. Bare in mind that the first iteration is selected by passing 1 into the pseudo class, not 0 like arrays for example.
There are also other key features of the nth-child() pseudo class; as well as passing in numbers like I have shown previously, the pseudo class also supports key words such as even or odd like so.
//Applies styling to every even instance of the class .blue
.blue:nth-child(even) {
color: blue;
}
//Applies styling to every odd instance of the class .blue
.blue:nth-child(odd) {
color: blue;
}
This can also be taken further; a formula can be expressed as to exactly which elements the styling is to be applied to.
The formula is expressed an+b, where a is the frequency of the elements to select, and b is the offset. So the formula 3n+4 will apply styling to the fourth element, and every third element beyond that. (4, 7, 10, 13, 16, etc...). Below is an example of how this can be applied.
//Style every 6th instance of the class .blue, starting with the second element. (2, 8, 14, 20, 26).
.blue:nth-child(6n+2) {
color: blue;
}
If no offset is required then simply pass in the same formula as before, dropping the offset at the end; passing in 4n is an example of this.
I hope this helps, I feel that this pseudo class is very powerful, and equally under rated by a lot of people.
There is no first-of-class selector.
See BoltClock's answer (CSS3 selector :first-of-type with class name?)
There is a work around but it didn't work for me
Related
What is the difference between selecting in the DOM with these formats '.selector' and '[class="selector"]'?
I would expect the same result using either of both, but the element is not found when using the second variant. Why?
> document.querySelectorAll('[class="cropped-profile-image__picture"]')
NodeList []length: 0__proto__: NodeList
> document.querySelectorAll('.cropped-profile-image__picture')
NodeList(2) [div.cropped-profile-image__picture.cropped-profile-image__picture--type-cover, div.cropped-profile-image__picture.cropped-profile-image__picture--type-profile]
.selector matches any element which has any class selector. I.e. it will match class="selector foo".
[class="selector"] matches any element that has exactly the value "selector" in its class attribute. I.e. it will not match class="selector foo".
The difference being that .something selects all elements that have something class on them - even if they have other classes. While [class='something'] only selects those elements that have only one class 'something'.
In the snippet below, you can see that .something applies a red border to both boxes, while the [class='something'] selector applies a background color to only the first box.
div {
width: 100px;
height: 100px;
margin: 5px;
}
.something {
border: 2px solid red;
}
[class='something'] {
background-color: blue;
}
<div class="something"></div>
<div class="something else"></div>
When you use an attribute selector, you are attempting to match exactly the string that you pass. The class attribute would need to be cropped-profile-image__picture, nothing more, nothing less.
For example, the following <div> would match your first query selector:
<div class="cropped-profile-image__picture"></div>
But this one wouldn't:
<div class="cropped-profile-image__picture another-class"></div>
Because the class attribute doesn't exactly reflect what you have queried.
When you query a class using a period (querySelectorAll('.cropped-profile-image__picture')) you are using a DOM API that will return elements that have that class, whether they have more classes or not.
The selector only selects exact matches, but the elements also have the class
cropped-profile-image__picture--type-cover
Can anyone explain me what does the below css do?
.validate-error .validate-error {
color: #cc2424;
display: inline-block;
margin-top: 5px;
}
.make-switch + .validate-error {
margin-left: 10px;
}
In the first css i see the same class name used twice?. Is this css valid?. I came across this thread
What is the difference between the selectors ".class.class" and ".class .class"?
but unsure whether its applicable if we use the same class name twice?.
The first one styles child elements/descendant with the same class name:
<div class="validate-error">
This color may be different from #cc2424
<div class="validate-error">Has color #cc2424</div>
</div>
This means: The styles are applied/overwritten for child elements with the same class name.
The second one styles siblings:
<div class="make-switch"></div>
<div class="validate-error">Has left margin</div>
<div class="validate-error">Has no left margin</div>
That means: Only if .make-switch is followed by .validate-error the styles are applied to .validate-error.
Demo
Try before buy
.validate-error .validate-error {
...
}
This css targets a class .validate-error that is a descendant of .validate-error.
For example
<div class="validate-error">
<div class="validate-error">
</div>
</div>
Next css targets the class .validate-error when it is right next to .make-switch
.make-switch + .validate-error {
...
}
when selector parts are stuck together without whitespace it means it should all match the same element.
example: (should only match an element having both validate-error and other-class as classes)
.validate-error.other-class
when there is whitespace between them you are selecting an element that has other-class as a class and has a parent element with the validate-error class
the + in your second selector actually means you don't want a child of make-switch but you want the sibling element, but only if it has class validate-error
Yes it is valid. There are no rules in CSS preventing a class name appearing multiple times in a complex selector. There are no rules in HTML preventing two elements, one of which is a descendant of the other, from sharing membership of a class.
Id only should be unique, but classname we can use multiple times.
I have a situation in which I load a style with a selector that should be prioritized over another.
The situation looks like the one in this fiddle, in which a specific id selector is not being prioritized over another one that uses a class that is under a specific id.
--HTML
<div id="cont">
<p class="hello" id="hello">I wish I was blue</p>
</div>
--CSS
#hello {
color:blue;
}
#cont .hello {
color:red;
}
Result is red text
I'm pretty sure this could be possible without using !important - which I really would like to avoid since this will be maintained by designers with no css skills for A/B testing. I want to make a selector for them that they will only edit it's properties.
Edit: To be clear, the #hello selector is injected to the page and I want to change it to one that actually works, but I don't want to change the other selector for that purpose. Of course if I have no choice I will, but it seems reasonable to be that this css is valid as it is and overriding that selector should be possible without modifying it.
Simply use the :not selector to exclude the #hello element.
Change the first to:
#cont .hello:not(#hello) {
color:red;
}
Demo Fiddle
More on :not from MDN
The negation CSS pseudo-class, :not(X), is a functional notation
taking a simple selector X as an argument. It matches an element that
is not represented by the argument. X must not contain another
negation selector, or any pseudo-elements.
Alternatively- per the comments below, you can increase the specificity of the second selector whilst providing variations for various contexts:
#hello, #cont #hello, #hello.hello {
color:blue;
}
Demo Fiddle
I suggest you to add another id selector to the first set of CSS rules.
#cont #hello {
color:blue;
}
#cont .hello {
color:red;
}
DEMO http://jsfiddle.net/a_incarnati/53q74jah/
In this case the color was overridden in red because you were using just one id selector #hello and that it's less specific than a selector with 2 ids combined or one id and one class combined, like you have done:
#cont .hello {
color:blue;
}
One of the things to take into account when writing CSS code, it’s the concept of CSS specificity. Understanding well this concept will avoid you to have to use !important;
As Mozilla Developer Network defines it, specificity is nonetheless:
Specificity is the means by which a browser decides which property
values are the most relevant to an element and gets to be applied.
Specificity is only based on the matching rules which are composed of
selectors of different sorts.
The following list of selectors is by increasing specificity:
Universal selectors
Type selectors
Class selectors
Attributes selectors
Pseudo-classes
ID selectors
Inline style
You can measure specificity counting how many selectors are present in a CSS statement.
CSS Specificity can be represented by 4 columns of priority:
inline=1|0|0|0
id=0|1|0|0
class=0|0|1|0
element=0|0|0|1
Left to right, the highest number takes priority.
You don't need two different selectors. You can keep one:
.hello {
color:red;
}
#cont .hello {
color:blue;
}
http://jsfiddle.net/vkftfj2n/4/
I have this HTML:
<h2 class="first second">Red</h2>
<h2 class="second">Blue</h2>
<h2 class="first">Green</h2>
How can I select h2 with first and second class?
thanks about answers
Update:
If I have another h2 tag like this:
<h2 class="first second third">Default</h2>
it will be red with h2.first.second selector. Is there any way to select only element with first and second classes, not more.
Simply:
h2.first.second {
color: red;
}
This selects the h2 element with both classes "first" and "second". Refer to the CSS Selectors Level 3 W3 recommendation for more info.
JSFiddle demo.
If you are trying to select h2 with first and second class simutaneously
h2.first.second
I have created a working CodePen example of the solution.
h2.first.second {
/* styles go here*/
}
To select elements that have multiple classes simple use this:
h2.first.second
Note that there is no space between the classes, as apposed to the following which would select elements with the class of second which are inside a h2 element with the class of first
h2.first .second
You can select
.first.second {}
if you want only the first h2 to be selected. Make sure there is no space!
The following rule matches any h2 element whose class attribute has been assigned a list of whitespace-separated values that includes both "first" and "second":
h2.first.second { color: red }
Reference
But, to select an element whose class attribute exactly equal "first" and "second" I used this rule:
h2[class="first second"], h2[class="second first"] { color: red }
JsFiddle demo.
Can any body tell me how I use last-child selector to style my last div of subs?
This is my HTML -
<div class="main">
<div class="subs"></div>
<div class="subs"></div>
<div class="subs"></div>
<div class="subs"></div>
<div class="paginate"></div>
</div>
I tried it something like this in my CSS -
div.main div.subs:last-child {
border: none;
}
But its not working. If I remove paginate div, then it is working. So can I know how can I style last subs div without any extra id or class declaration.
Thank you.
Assuming there is only ever 1 element succeeding your .subs (.paginate), you can use this:
div.main div:nth-last-child(2) {
border:none;
}
See this JSFiddle
This can be seen as a little hacky, and if your paginate element is ever absent, then the wrong sub element will be targeted. Your only other option is to give the .subs their own container and then use :last-child:
Another JSFiddle
P.S: To understand why :last-child isn't working the way you want it to, I really recommend also reading Spudley's answer.
The problem you have is because of :last-child doesn't work the way you think it does.
The :last-child selector will select an element only if it is the last child of its parent.
In the case of your .main element, the last child inside it is the .pagination div. This means that .main>*:last-child can only select the pagination div. It doesn't matter if you filter it down by specifying .subs; you can't select anything else using :last-child because none of the other elements are the last child of .main. If the actual last child element isn't in the filtered selection, it will select nothing rather than selecting something that isn't the last child.
The best way to work around this is to wrap your subs elements inside an additional layer of markup, so that the last one then does become the last child of that container element. Either that, or move the pagination element outside of the main element; whatever works best for your layout.
The other selector you might have tried, :last-of-type works in a similar way. For the time being, there isn't a CSS selector you can use instead to pick the last .subs element, using your current markup. (unless you're happy to go with :nth-last-child(2) which will pick the second-last child, on the assumption that the pagination div will always be present).
In the new selectors being designed for CSS4, there is a set of 'match' selectors that would do exactly what you want to do. You would use :nth-last-match(1) to get the last matching element. This is the selector you need. Unfortunately, it isn't available in current browsers, and there's no real hint yet as to when (or even whether) it will be available in the future. For the time being, you can read about it here, but not use it. You might be able to use it or something similar via a JS library like jQuery.
Hope that helps explain things to you.
I would suggest that you add an extra class name to the last element. http://jsfiddle.net/5FQck/
div.main div {
border: #000 thin solid;
}
div.main div.subs.last {
border: none;
}
<div class="main">
<div class="subs">subs</div>
<div class="subs">subs</div>
<div class="subs">subs</div>
<div class="subs last">subs</div>
<div class="paginate">pagination</div>
</div>
None of the following selectors work in IE 8 and below, primarily because they are all CSS3 selectors.
:nth-child(N)
:nth-last-child(N)
:nth-of-type(N)
:nth-last-of-type(N)
You could also add that new class to the last element using JQuery: http://jsfiddle.net/5FQck/1/
$('div.main div.subs:last').addClass('last');
If I understand you correctly, I would do it like this.
.main .subs:nth-child(4)
{
border:none;
}