CSS Style Nesting - Proper Form? - css

I am having a problem trying to find any specific details on how to properly write CSS rules in a stylesheet where the class or ID is nested within many other IDs and styles, e.g.
.mainbody #container #header #toprightsearch .searchbox {}
So here we have a searchbox class within a toprightsearch ID, in a header ID, in a container ID, in a mainbody class.
But it appears to work properly if I omit some of the IDs.
What is the correct way of listing these?
If I include all of the parents does it make it more specific?
Can it error on different browsers if I don't include all?
And any additional information on this topic would be appreciated.
Thanks

.searchbox {}
Styles anything with .searchbox
.mainbody .searchbox{}
Styles any .searchbox that descends from any .mainbody, direct child, grandchild, quadruple great grandchild, doesn't matter.
#toprightsearch > .searchbox {}
Styles only .searchboxes that are direct children of #toprightsearch
#container * .searchbox {}
Styles .searchbox's that are grandchild or later of #container.
Here's a good document on the topic: w3C selectors

If you include more parents, it does increase selector specificity. You shouldn't have cross-browser problems omitting parents.
There is no correct number of parents to list; it depends on what you require for your markup. As you're seeing, selector1 selector2 means a selector2 at any level inside a selector1, and you can tune that for whatever behavior you need.
In your example, you should list .mainbody #container #header #toprightsearch .searchbox if what you mean is for the style to only apply to .searchboxes that are inside that entire hierarchy. If contrariwise you want .searchboxes that exist other under conditions to get the same style, you should be less restrictive in the hierarchy. It's only about what you're trying to accomplish.
Re comment: IDs produce more specificity, so omitting them reduces your rule's specificity more.

Id's are specific to the page. So you'd just use
#toprightsearch {
stylename: stylevalue;
}
If your looking for nested classes then the correct format is
.header .textBoxes {
stylename: stylevalue;
}
If you know the exact child of a parent then you use the > sign. So if your document was like this:
<div class="header">
<div class="menu">
<input type="text" class="textBox" />
</div>
</div>
You can use this:
.header > .menu > .textBox {somestyle:somevalue;}
This means only items with a .textBox class directly inside of a .menu class item which is itself directly below an element with a class of .header.

From the W3 Selectors Documentation:
Descendant selectors express such a relationship in a pattern. A descendant selector is made up of two or more selectors separated by white space. A descendant selector of the form "A B" matches when an element B is an arbitrary descendant of some ancestor element A.
So in short, no you do not have to include all of the parent elements, and should not cause any cross-browser problems. However, with this selector:
.mainbody .searchbox {}
The styles defined will apply to any element with a class of searchbox whether it descends directly or indirectly from an element with class mainbody.
With your proposed selector, however:
.mainbody #container #header #toprightsearch .searchbox {}
The styles defined are more specific, and so only elements that descend from an element with class mainbody, then the elements with IDs of #container, #header, #toprightsearch in that order and that have a class name searchbox will have the defined styles applied.

Theoretically, an ID should only be used for one specific item on a page. So you should only have one item with an ID of toprightsearch so, for your CSS to work you only need to indicate:
#toprightsearch .searchbox {}
because there is only one item on your page with an ID of toprightsearch, All the other selectors are unnecessary.
If you have two items on your page with an ID of toprightsearch then that is bad coding practice.

The code below does what it says (at least in Firefox). it colors the input red
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Document</title>
<style type="text/css">
.mainbody #container #header #toprightsearch .searchbox {
background-color:red;
}
</style>
</head>
<body class="mainbody">
<div id="container">
<div id="header">
<div id="toprightsearch">
<input type="text" class="searchbox" />
</div>
</div>
</div>
</body>
</html>
I think you should see if there went anything wrong in spelling the ID's and classes.

Related

What does "div.container" and mean in CSS

Currently tweaking a theme and have tried searching for an answer to this question to this! I'm not stuck - but more just want to know the answer out of curiosity.
I understand that
"#" means an id and
"." means a class.
I've also been reading on this post about how you can add specificity to your html/css through combination of elements/ids/classes ie:
a.fancy { color: red; } /*an element that has an anchor and a class = red.*/
However the code I am working on has the following elements that I don't understand:
div.footer {background-color: {{ settings.footer_color }};
Why would you specify "div.footer" as both the div and the class when simply using a "." would suffice? In my mind there would be no point when the class ".footer" could be used without a div?
Hope you can help me work this one out!
div.footer means the element must both BE a <div> and HAVE the class footer.
.footer would trigger for any element with class footer; for example, a <span class="footer".
div.footer means you are targeting only <div> elements with the class .footer.
<div class="footer">This is targeted.</div>
<p class="footer">This isn't targeted, as it isn't a div with the class .footer.</p>
div .footer, however, would target all elements with the class .footer that are descendants from <div> elements.
<div><p class="footer">This is targeted.</p></div>
<section><p class="footer">But this isn't targeted.</p></section>
With the new implementation of html5 <footer> is a legitimate tag just like <div> or <p>. As confusing as it may be the period . before the footer declaration constrains it to a class name instead of the tag.
So in your case: div.footer = <div> with class name footer = <div class="footer>.
There are numerous reasons why you may make such a declaration.
Sample html
<div>
<div class="footer">Footer only</footer>
<div>Div only</div>
<footer>Footer tag; DIFFERENT</footer>
</div>
Example Css
div {
border: 1px solid red;
}
.footer {
background: blue;
color: #fff; /* white font color */
}
Depending on what you want to do, let's use the specific div.footer examples to show what we can do.back
Inheritance
By inheritance, div.footer will inherit "3 properties" -> background, color and border from the div and .footer declarations.
Now you may want to override some of these properties so...
Overriding Property
Use something like div.footer { color: red; } this will override the white color.
Layout Insight
The beauty of css is that you can use declaration to give you "insight" on what the html markup will be laid out as.
Omitting properties I would write the css as follows:
#footer {}
#footer ul {}
#footer ul li {}
#footer p {}
#footer p a {}
The html:
<div id="footer">
<ul>
<li>List 1</li>
<li>LIst 2</li>
</ul>
<p>Hello! Copyright website company name.</p>
</div>
You could then reverse engineer the html through just css because of the descendent character use. This maximizes the power of "cascading".
--
NOow I hope some of this has given you some insight. A few other pointers are this:
Typically a webpage has only one footer. When there is only one of something use the # id selector ALWAYS.
Use classes to not only apply styles to multiple elements but to also provide "meaning to your markup" -> go back to the principle of "layout insight" to understand what I mean.
div.footer should could more simply be .footer Now, it may be necessary to include div just to say "I only want to apply this class to divs only" and in that case go for it. But defining all your declarations with div.someClasName is not all that valuable.
DO NOT use names of tags as classnames. div.div is very confusing - especially if you are programming for a while. Therefore, since <footer> is now a legit tag you shouldn't apply it as a classname. On the other hand "#footer" could be argued differently because it can only exist once in a webpage.
It's about specificity. div.footer is more specific (a div with that particular class) than .footer (any element with that class).
As to when to use one or the other, it really depends on the markup and CSS you are building.

What is this CSS selector? [class*="span"]

I saw this selector in Twitter Bootstrap:
.show-grid [class*="span"] {
background-color: #eee;
text-align: center;
border-radius: 3px;
min-height: 30px;
line-height: 30px;
}
Does anyone know what this technique is called and what it does?
It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.
So would select the <strong> element in this example:
<div class="show-grid">
<strong class="span6">Blah blah</strong>
</div>
You can also do searches for 'begins with...'
div[class^="something"] { }
which would work on something like this:-
<div class="something-else-class"></div>
and 'ends with...'
div[class$="something"] { }
which would work on
<div class="you-are-something"></div>
Good references
CSS3 Attribute Selectors: Substring Matching
The 30 CSS Selectors you Must Memorize
W3C CSS3 Selectors
.show-grid [class*="span"]
It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.
The Following:
.show-grid [class*="span"] {
means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.
<div class="show-grid">
<div class="span">.span</div>
<div class="span6">span6</div>
<div class="attention-span">attention</div>
<div class="spanish">spanish</div>
<div class="mariospan">mariospan</div>
<div class="espanol">espanol</div>
<div>
<div class="span">.span</div>
</div>
<p class="span">span</p>
<span class="span">I do GET HIT</span>
<span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>
<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>
All of the elements get hit except for the <span> by itself.
In Regards to Bootstrap:
span6 : this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thus span6 would have a width of 50%.
In the current day implementation of Bootstrap (v.3 and v.4), you now use the .col-* classes (e.g. col-sm-6), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadays
It selects all elements where the class name contains the string "span" somewhere. There's also ^= for the beginning of a string, and $= for the end of a string. Here's a good reference for some CSS selectors.
I'm only familiar with the bootstrap classes spanX where X is an integer, but if there were other selectors that ended in span, it would also fall under these rules.
It just helps to apply blanket CSS rules.
In my case I'm unable to apply background color for class due to dynamic change of class name with numbers
Ex:
Issue:
body .ForwardRef-root-198 .aura-ag-grid .ag-row:hover, body .ForwardRef-root-198 .ag-details-grid .ag-row:hover {
background-color: #2196f35c !important;
}
Solution:
body div[class*="ForwardRef-root-"] .aura-ag-grid .ag-row:hover, body div[class*="ForwardRef-root-"] .ag-details-grid .ag-row:hover {
background-color: #2196f35c !important;
}
Reference: link

css explained for selecting the aplicable element

Can somebody please explain what the selectors mean?
As far as I understand having #myId - is css for control with id=myId.
.myClass is Css for controls with class myClass.
Can somebody please explain the other combinations?
div.img a:hover img
{
border:1px solid #0000ff;
}
div.desc
{
text-align:center;
font-weight:normal;
width:120px;
margin:2px;
}
div.img a:hover img
selects images that are inside hovered links, that are inside div elements with class img, and gives them a blue border.
div.desc
selects divs with the class desc.
An id (#) can exist only once in a document. It is really useful to identify an element in CSS ans in JavaScript as well (should you ever need it).`
A class (.) can be used as often as it is required.
Example: you have only one header: <div id="header">Header</div>, but several articles: <div class="article">...</div>
Say you have this HTML document:
<div id="site">
<h1>Some heading...</h1>
<div class="article">
<h1>Title</h1>
<p>Some content...</p>
</div>
<div class="article">
<h1>Title</h1>
<p>Some content...</p>
</div>
</div>
The heading of the articles shouldn't be as big as the heading of the site, so we have to use a more specific selector: .article h1 {...}. This will style every <h1>element in a element of the class "article".
If we want to have an even more specific selector, we would use: div.article h1 {...}. This will only style every <h1> element in a <div> box with the class "article"
div.img a:hover img means: find me an img element which is a descendant of an a element that is currently being hovered over, which is in turn a descendant of a div element with a class name og img.
div.desc simply selects any div with a class name of desc.
Have a look at the standards definition, I always find this useful: CSS selectors at W3C.
div.img a:hover img
This will match any img tag that is within an a tag which is currently in a hover state that is within a div tag that has class="img".
div.desc
This will match any div tag with class="desc".
When items are chained like this with only spaces between them, it matches on that specific hierarchy of elements. For example, in the first one, an img tag that's not in an a tag won't be matched.
You can also delimit items with a comma, which instead of matching a hierarchy of items will match each item individually. So something like div.img, img will match any div tag with class="img" and will match any img tag.
Specifically for the :hover attribute, that's called a pseudo-class. It modifies the attribute to which it's attached (in this case an a) by looking for items of that type which are in a specific state (in this case, being hovered over).

CSS :first-child to work with classes

Say i have this markup:
<div class='current'>
</div>
<div class='current'>
</div>
<div class='current'>
</div>
<div class='current'>
</div>
<div class='current'>
</div>
Now these divs are not necessarily next to each other in the markup, but could be spread throughout the page.
Can i target only the first occurrence of class "current" using CSS only, i'd ideally like to avoid using javascript (for now)?
Ie.
.current:first-child {
background: red;
}
I believe you're looking for something like this:
.current:nth-child(1){
background:red;
}
Should do the trick!
:first-child targets elements that are first children, not first occurrence of a given class. So this will target all elements with current class, that are first children. It can be all of them if they are in different places on a page or none at all.
It sounds like you may be looking for css3 selector first-of-type
As mentioned in these two answers (along with this new one), CSS3 doesn't bake in a pseudo-class that selects the first element of its class (unlike :first-of-type which selects by type).
You can always use :first-child if .current is guaranteed to be the first child of .group:
.group .current:first-child {
background: red;
}
But if it's not guaranteed to be, then based on your comments and the answer link, since they all share the same parent you can do this instead:
.group .current {
background: red;
}
.group .current ~ .current {
background: transparent; /* Or whatever your default is */
}
The general sibling combinator ~ ignores other elements that may not be .current. All these rules work in IE7+.
If they are spread throughout the page, you can not get what you need with pure CSS solution. Even with first-of-type unless the elements are on the same DOM level. Check the example to see that you can not select the elements.
On the other hand once I move the third .current to the same DOM level where I already have the second one, I get only the second item selected, as it's the first .current on this level.
On the other hand it's a very short one-liner in JS
Don't overcomplicate things ;)
If it's spread throughout the page, you can't target it with css.

What is the purpose of the 'div' selector and why do so many developers use it in their style sheets?

Looking through style sheets from popular & unpopular websites I have found the div selector included in them. The bottom four examples were taken from the style sheets of the popular sites Stack Overflow, Github, Youtube & Twitter:
div.form-item-info{padding:4px 0 4px 4px;width:80%;color:#777;}
.searchFooterBox div span.smallLabel{font-size:14px}
#readme.rst div.align-right{text-align:left;}
.hentry .actions>div.follow-actions{visibility:visible;text-align:left;}
I find that I can design fully functioning CSS style sheets with out using the div selector so the question is:
What is the div selector's function?
&
Why do so many developers use it?
EDIT:
To be clear, when using the div selector, what does it mean when div appears before an id or class?
For example:
div.foo { color:black; }
div#bar { color:gray; }
And what does it mean when div appears after an id or class?
For example:
.foo div { color:black; }
#bar div { color:gray; }
When the div selector appears after an id or class does it have to have another selector appear after it?
For example:
#foo div span { color:black; }
#foo div p { color:black; }
Being more explicit in your selector makes it easier to remember what the HTML structure is like. Months down the line I can read the CSS and based on my explicit rules I can automatically map the structure in my head without going back to the HTML.
By specifying the node name before the class or ID, the rule becomes more specific. If you want to override .foo { color:black; } for a div that has a class of foo, just do div.foo { color:red; }. Paragraphs that have a class of foo would be black, while divs would be red.
It can be useful if you want to serve different css rules based on HTML structure. In the rules below, Any span inside a div is red. Any direct span under #foo is blue.
CSS:
#foo div span { color:red; }
#foo span { color:blue; }
html for that:
<div id="foo"><span>blah</span> <div><span>blah</span></div> </div>
Live demo that you can play around with: http://jsfiddle.net/6dw2r/
EDIT:
div#foo matches a div with an id of foo.
div#foo div means any div descendants of #foo.
No. It doesn't.
Please read http://www.w3.org/TR/CSS2/selector.html#pattern-matching for further questions.
div.form-item-info{...} // all div elements that have class~=form-item-info
.form-item-info{...} // all elements that have class~=form-item-info
In HTML and XHTML, <div> and <span> are generic container elements. <div> is a block-level element. <span> is an inline element.
Most other elements (<h1>, <p>, <strong>, etc.) have specific semantic meanings. It's bad practice to use, say, a <p> element for something that's not a paragraph. But <div> is just a container.
If you need something to be purely decorative, or to group related elements, <div> is a good choice.
The tag defines a division or a
section in an HTML document.
The tag is often used to group
block-elements to format them with
styles.
http://www.w3schools.com/tags/tag_div.asp
They're just being explicit about their selectors, which tends to be a good thing, as you're being more specific when addressing the elements to be styled. (Smaller chance of conflicts and unintended styling.)
div.foo { rule }
div#bar { rule }
This means the rule only applies to div elements with class foo or id bar, and the rule would not apply to non-div elements with class foo or id bar.
.foo div { rule }
#bar div { rule }
This means the rule applies to all div elements inside any element with class foo or id bar. This is called a descendant selector.
#foo div span { rule }
#foo div p { rule }
When a div selector appears after an id or class, it is not required to have another selector after it. If there is such a selector, the rule will apply to the selected elements only if they are inside a div element which is inside an element having id foo.
You may want to read up on your selectors here:
http://www.w3.org/TR/CSS2/selector.html

Resources