Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a <div> element inside a <li> element (as shown in code snippet). The <li> element has cursor: pointer style property set and I can't remove the cursor pointer in that nested <div> element.
The <li> is not in our control to remove css, since it comes from a third party.
.container {
cursor: pointer
}
.local {
cursor: default !important
}
<ul>
<li class="container">
<div class="local"> Hello World </div>
</li>
</ul>
The .container class is actually irrelevant here. It just so happens that it has a cursor: pointer property which shows on, but the problem is in fact - What is overriding the .local classed <div> element from rendering the cursor: default property.
The best way to answer that would be to take a look at the elements and styles panels on your browsers developer tools and see what's doing that. It will let you know what's overriding it.
Then you can use adjustments, either by increasing specificity, or by changing the code that's overriding it. But the specificity needs to be relevant in comparison with the .local class and whatever is actually overriding it.
Edit: In the provided example, you don't need to worry about specificity because they're different classes. However, I frequently see !important being added to rules as a lazy way to override specificity issues that aren't replicated in the example. I assume that to be the case here as well since the OP notes that, "the container comes from a third party". So understanding specificity rules will help resolve the issue.
You could use !important but that should really be a last resort. However, you're much better served long term by increasing CSS Specificity.
Currently .container & .local have equal weight. You can increase specificity by: Using an ID, referencing more hierarchy, using combinators etc. Then the NEW attributes will override the previous attributes based on CSS order.
Eg:
.element {
background: blue;
}
.element {
background: red;
}
// produces a red element
So in this case you want to increase specificity. You can do that easily like this:
.container {
cursor: pointer;
}
.container > .local {
cursor: default;
}
// where local is a DIRECT child of .container
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am linking a CSS file to a django app page. The HTML is from ajax, some of the css is getting applied, but most is not. For example, at the top of the CSS file I have the following:
$green: #86BB71;
$blue: #94C2ED;
$orange: #E38968;
$gray: #92959E;
div.nothingdiv{}
div#fav_studyspot_chat{
margin: 0 auto;
width: 750px;
background: #444753;
border-radius: 5px;
}
The second div only works after I put in the nothingdiv. Can anybody explain what that would happen?
The use of $-prefixed variables isn’t supported natively in CSS: it’s a feature of CSS compilers such as Sass and Less. In CSS, the only top-level declarations you can write are:
selectors, which describe elements (e.g. via class names, IDs, or element names)
media queries, which describe different styles under different conditions
keyframes, which describe animations
and imports, which allow you to import other style sheets
When a browser encounters code that isn’t one of these kinds in CSS, it ignores it until it encounters code it understands, which usually means waiting until it encounters curly braces that denote the end of a declaration }.
If you remove all the variables with the dollar signs in front of them, your code should work even without the fake styles.
If you want to use variables in CSS, and not have to have them compiled by Sass or Less, you should use custom properties, which look like this:
:root {
--green: #86BB71;
}
.element {
color: var(--green);
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In an online tutorial, I was recently told to create a class for nav elements called "nav". I'm a beginner in CSS, but is it just me, or is this redundant/confusing/bad practice?
NO it's not redundant.
YES it's redundant if you think in your specific case you're fine with nav{ /*blaah blaah*/ }
<nav> is a Semantic HTML5 tag that represents toward SEO a navigation. A navitagion is all you want it to be. So in the case you have multiple nav elements in our page and you're OK to target-styles directly the tag element using nav I'll be glad to see that.
It's not redundant. The DOM element nav is different from the CSS class nav.
If you wanted to style this element by class, you would use this style declaration (for example):
.nav { background-color : #F00; }
if it were styled by element type it would be:
nav { background-color : #F00; }
This may seem trivial, but that period . makes a difference. It means you are identifying the item by class and not by element name. If you use the class syntax (with the .) then you could also write:
<div class="nav"></div>
This would show with a red background if you included the class definition, but not if you styled the element type directly.
In simple applications you may be able to get away with directly styling element types (e.g. <nav>) as opposed to classes (e.g. class="nav"), but as you get more complex layouts you are going to want to use classes. Additionally, if you use a selector-based library like jQuery, or document.querySelect() you may have good reasons for specifying a class.
If you truely can know that all <nav> elements can be styled the same in all your pages, then by all means just use the element selector, but to leave yourself flexibility it's best to use classes.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In the following article I read that one should try reduce the number of selecetors.
Article: use less selectors
I'm wondering if writing LESS and I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
LESS
.wrap{
width: 100%;
height: 20%;
background: green;
header{
background: blue;
h1{
color: red;
}
}
}
I'm using a lot of nesting to group parent and child elements, will that generate bad CSS code in the end?
In a word, yes. In the long run this will give you highly specific, unmaintainable CSS. Let 's have a look at what your example will produce for the h1 style.
.wrap header h1{ color: red; }
So what you've ended up with here is a very specific CSS selector, that isn't really necessary. You could, for instance, just have
h1 { color: red; }
or use a class on the h1
.title { color: red; }
Why is specificity bad?
So imagine, 6 months later another developer comes along and they need to change the color of a h1, but just one of them.
First they try to add a class to the h1
.new-color { color: blue; }
But the colour doesn't change because the original CSS is so specific. So they have to do this
.wrap header h1.new-color { color: blue }
or worse still they may do this
.new-color { color: blue!important; }
And then what happens when other changes need to be made? As you can see very quickly and very easily you can end up with unmaintainable CSS, that will have everyone pulling their hair out.
Performance
People usually negate performance when it comes to CSS, but it is always good to know what is going on when a page is rendered. CSS is read from right to left. Using your example
.wrap header h1 { color: red; }
This means the browser engine will search for every h1 and check if they have a parent header and then if that has a parent class wrap. If so it will apply the style. A low specificity makes the rendering process a lot simpler.
Summary
So to sum it up, nesting, whilst it may seem great keeping your code nice and readable, should only be used when absolutely necessary. It's very easy to forget what the CSS that is actually being produced looks like. Before you know it you'll be in nesting hell.
Languages like LESS or SASS give you more flexibility in declaring your style rules, and that can be good or bad depending on how you use it. The more flexibility you have in a language, the more you need design patterns and good practices to avoid making things worse than they were before.
LESS doesn't require that you always nest. You can always use CSS of course, and if you are applying a style to all p it might be better to define it globally, than to call mixins to obtain the same result on several nested ps.
But LESS and SASS do allow you avoid duplication, to write code that is clearer and easier to maintain, and other problems caused by the code duplication required by CSS.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am mostly a backend programmer, and am relatively new to CSS. So far, I hate it. My biggest complain is that is incredibly redundant and difficult to produce readable code.
Many times I need to apply styling to different but similar elements. However, I find it incredibly challenging to produce elegant code to do that.
The most simple way to do things in CSS seems to be to give an ID to everything and use custom code for every single element in the page, or classes when there are repeated elements with. However, this still leaves a lot of repeated code, like when I have two elements that are almost exactly alike, but have one or two different attributes, like width, background color, color or float side.
My current solution is defining many atomic classes, like
.bgRed { background-color: red; }
.bgBlue { background-color: blue; }
.fontCenter { text-align:center; }
.left { float: left; }
and so on, and applying multiple classes to an element, like this:
<span class='bgRed left' >My text</span>
But that's still very short of decent. Some attributes, like width and height, are usually strongly tied to it's elements, so I can't create an atomic class for it, and end up resorting to using it's ID.
Finally, my question: Why doesn't CSS support some kind function-like structure? Would a feature like this be useful in CSS? Is CSS badly designed or I just don't know how to use it properly? Why was CSS designed the way it is?
How I imagined functions in css would work:
Defining a css function:
_sidebar(float_side, color, width){
float: float_side;
backgroud-color: color;
width: width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
And applying:
<div cssfunc='sidebar(left, #FF0000, 150px)' >
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
Bonus question: How do you maintain you CSS code readable and organized, with minimal code repetition?
This is not the intended usage pattern for CSS. A general clue is if you have specific formatting words like colors or alignments in your class name, you're not following the "spirit" of CSS.
The intention for CSS classes is to use semantic categories for class names. For example instead of having a class named bgRed, use one called warning. The difference might be subtle in some cases, but the difference in philosophy usually helps maintenance. Instead of combining "literal" css rules at the element level, you'd combine more meaningful semantic ones like class="sidebar warning".
With that said, some people still find the lack of reusability of formatting between CSS rules cumbersome. There are fixes for that as well. The best solution is to use a CSS pre-processor like LESS or SASS. These languages compile into CSS, but support things like mixins and variables that function very much like the css enhancement you have in mind.
HTML defines what to show, CSS defines how to show it. If you use classes like "bgRed" or "left", you are doing this old way.
CSS doesn't define support functions, but LESS does. Imagine this:
.sidebar(#side, #color, #width) {
float: #side;
backgroud-color: #color;
width: #width:
height: 200px;
color: #FE02A5
list-style: none;
display: table;
}
.sidebar-important {
.sidebar(left, red, 100px);
}
.sidebar-misc {
.sidebar(right, blue, 50px);
color: grey; // overwrites .sidebar function
}
Then in HTML:
<div class="sidebar-important">Important news</div>
<div class="sidebar-misc">Something else</div>
This way, you can easily change values in LESS file, compile it to CSS and you won't need to change it in HTML.
Bonus answer:
LESS.
In designing the HTML and CSS for a page, when should I use
img.className
versus
.className
versus
#idName
or some other variant?
Are there guidelines or recommendations?
Summary from answers
Thank you to all answerers - there is some excellent stuff here!
make CSS as specific as possible
use an OO approach
order: #id, tag, tag.className, .className
when to use each selector, also class/ID comparison
give selectors names based on purpose, not what they look like
use advanced selectors for smaller code, leave CSS classes for exceptions/overrides only
manage ASP.NET munging ID
In general you should be as specific as the item demands.
There is no general rule, it depends on the style in question.
A lot of people will recommend you keep to the lowest specificity with the theory that this allows the maximum cascading reuse but this is absolutely toxic in real world situations where you have multiple developers all working on slightly different versions of what a .foo might look like. Pollution from inheritance you did not want leads to massive bloat in trying to undo that locally or time-loss in refactoring.
The best guideline I always offer is to try and think of CSS in OO terms: class selectors map to interfaces more or less, tags map to classes, and ID selectors map to instances. Consequently decide if the style you want to apply really applies to that thing, all things like it, or anything which wants it.
I also strongly encourage you to make use of high level IDs on wrapper elements so you can write selectors in a namespace like fashion (i.e. #foo .bar, #foo .baz where #foo is unique to a page or set of page designs) which allows you both a level of specificity which reduces cross-design pollution and a level of generality which lets you make the most of cascading CSS reuse.
Best of both worlds.
It depends on the intended semantics, and, as others said, be as specific as possible.
#idName for unique elements on the page. Good examples are #header and #footer
TAGNAME for general purpose page styling.
TAG.classname and .classname for exceptions/overrides to the above rules.
And don't forget the use of advanced selectors. A bad example:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
.in_the_menu { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1 class="in_the_menu">My Menu</h1>
</div>
The same could have been achieved with:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
#mainMenu H1 { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1>My Menu</h1>
</div>
The second example gets rid of the superflous "class" attribute on the H1 element in the "mainMenu" div. This has two important benefits:
The HTML code is smaller and cleaner
You are less likely to forget to add the class attribute
If you take good care of you CSS, and make use of proper advanced selectors, you can nearly completely leave out CSS classes. And keep them only for exceptions/overrides.
Take this example which draws boxes with headers:
#content H2{
border: 1px solid #008789;
padding: 0em 1em;
margin: 0.2em 0em;
margin-bottom: 1em;
font-size: 100%;
background: #cccb79
}
#content H2 + DIV{
margin-top: -1em;
border-left: 1px solid #008789;
border-right: 1px solid #008789;
border-bottom: 1px solid #008789;
margin-bottom: 1em;
}
Now, as soon as you follow a H2 with a DIV in the #content element, you have a nice box. other DIVs and H2s are left alone:
<div id="content">
<h2>Hello Box!</h2>
<div>Some text</div>
<div>Some more text</div>
<div>Some more text</div>
<h2>And another title</h2>
</div>
If you get these rules right, you hardly ever need classes, and can work with IDs and TAG names alone. And as an added bonus, your HTML will be a lot nicer to read and maintain.
You preference should be, in order from highest to lowest:
id
tag
tag.className
.className
ID selectors are fast. Tag selectors are reasonably fast. Pure class selectors are slow because the browser essentially has to interrogate every element and see if each has that class. Getting elements by ID or tag name are "native" operations from a browser's context.
Also, I find it good practice to make your CSS selectors as restrictive as possible otherwise it just turns into a mess and you end up getting all sorts of unintended consequences where CSS rules apply where you didn't otherwise expect, which often forces you to create a similar yet different selector just so none of the rules regarding the first don't apply (translating into more mess).
Basically if you know if you only use a class on div elements then do this
div.className
not
.className
If you apply a class to several elements just list them:
h1.selected, h2.selected, h3.selected
instead of
.selected
In practice I find very few situations where you need to use "naked" class selectors or where it is advisable to do so.
you should use the selector best describing your rules
id: when you want to select one single element
.classname: when you want to style elements regardless of their tag
tag.classname: when you want to style only tags with the given class
tag tag tag: when you want to style all subelements of a tag
Class selectors
.className
This is to be used when you have more than one element on the page that you would like to apply the same style to. It can be to any tag element. So in the following all will use the same style as set out by the .className.
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
But you can also restrict it like so:
img.className
By placing the tag along with the style definition, you're saying that this style is only to be used when it's the class used by that particular tag, in this case, an image.
HTML code will look like this:
<img src="/path/to/image.png" class="className" />
If you have other elements on the page using the same class style, but are not of the same tag, then the styles set out in this will not be applied and they will take on the more generic version as mentioned in the first example.
So repeating the example above:
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
Only the image will take on the style as set out by img.className whereas all the rest will take on the style rules set in .className.
ID selectors
#idName
This is to be used when there is only one instance of a particular element that you wish to apply the style to.
You can also force it to apply only in certain tag conditions as you have earlier with the class definitions.
p#idName
This example will only apply to the paragraph block marked with the ID:
<p id="idName">
If you were to put that id on another element, like this:
<div id="idName"></div>
Then it will not take on the style set out and be ignored.
As to your two first selectors, the first of the two will overwrite the second, as it's more specific. You can calculate the specificity of a selector.
One thing worth noting is that some server side scripting technologies (most notably ASP.NET) don't play well with using IDs for your styling. If there is a chance your design will be used with such a technology, I recommend forgetting about #id selectors and use tag.className instead.
The reason is that ASP.NET actually changes the ID that ends up in the HTML based on a number of criteria, if the tag is output by a server side control.
I know this is a pretty old question but for all those who are reading this just now...
There are 4 categories of rules in general:
ID Rules, Class Rules, Tag Rules, Universal Rules.
And it's important to mention that class selectors are faster than tag selectors. So you should always use them in the following order
1. ID Selector
2. Class Selector
3. Tag Selector
4. Universal Selectors
In your case you should never use the tag name before class name.
You can find more information here: Writing efficient CSS
It really depends on the situation:
.error{
color:red;
}
p.error{
background-color:yellow;
}
div.error{
background-color:grey;
}
Always use the cascading effect of CSS to your advantage.
It's good practise to use the least specific rules you can for each rule.
How you structure your CSS will depend on the particular needs of the design.
Yes. You may want to use the same classname for two elements in the future. Be explicit and clear. This will also prevent class-rules from overlapping onto unintended elements.
h1.title { font-size:18px; } /* My h1's are big */
p.title { font-size:16px; } /* My p's are smaller */
.title { color:#336699; } /* All titles are blue */
Use ID's only when necessary, and only once per page.
When to use what depends on what you want to select. img.className (type selector + class selector) selects only IMG elements that’s in the class “className” while .className (just class selector) selects any element that’s in that class and #idName (id selector) any element with the ID “idName”.
But besides that, the selector all have a differente specificity that affects the order in which the properties of that rules overwrite the one of others.
So if you have an IMG element with the ID “idName” that’s in the class “className”:
<img src="…" id="idName" class="className">
The properties of the rules would be applied in the following order (specificity from highest to lowest):
#idName
img.className
.className
But when you use a specific class only for one specific type of elements (e.g. “className” only for IMG element), you can go with only .className.