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
I understand the title is a bit misleading, but I come from an Object-Oriented background, and I've recently began a shift towards web development. I've only got a basic grasp of HTML, and been learning and messing around with CSS, but there are some parts of it that are a bit confusing, and I'm trying to get it into terms I can understand.
My CSS:
.Person .span4 p
{
margin-left: 10px;
margin-right:10px;
margin-top:10px;
}
From what I can understand, this means that any p tag that is inside a container, like with the class of "span4", which is in turn inside another container that has class="Person" will be formatted with the specifications listed above.
In other words person.span4.p.format(String[] formatArgs), where the formatArgs are the margin-left, right, and top.
The Question: Is this an appropriate way to look at it?
I know it might be comparing apples to oranges, but I'd like to get an opinion before I go running with some conclusion that could be very wrong, and an actual explanation on how these work.
Your question about .Person .span4 p is correct, that will style a p element that's a descendant of an element with a span4 class that's a descendant of an element with a Person class.
However I wouldn't try to interpret classes in HTML as similar in any way to OO classes. They're completely different concepts, and I think that'll just end up confusing things.
Classes can be assigned to HTML elements using the class attribute (class="span4"), and these can then be used in CSS or JavaScript to apply additional styling or behaviours to those elements. Think of giving an element a class as tagging it with a particular keyword, so it can be easily targeted later. Elements can also be assigned multiple classes by separating them with a space, eg. class="span4 box".
In addition, .Person .span4 p isn't actually a "class", it's a selector. The .span4 syntax is called a class selector, the p is an element selector, and using a space between two selectors creates a descendant selector. Additionally #myId is an ID selector, and there are plenty of other types of selector as well.
I'd recommend this guide as a good way to get up to speed on the correct terminology.
Related
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 2 years ago.
Improve this question
I frequently need to address generic elements inside some specific sections of a page. I find this approach most easy to understand in terms of what any rule is affecting:
.shop > .products > .product > .description > .warning {
color: red;
}
But I often see this:
.shopProductsProductDesc > .warning {
color: red;
}
Does it really matter which approach is taken?
It really depends on the problem you are trying to solve.
The selector .shop > .products > .product > .description > .warning to my understanding would be used for two cases:
You have multiple warning elements but you only want to select the elements inside your description and there are other selectors used for warning that you don't want to overwrite.
You need to overwrite a previous selector that is less specific. Ex. .shop > .products > .product > .description .warning
The other selector .shopProductsProductDesc > .warning is less specific than the first one but assuming the container of .warning has those two classes .description.shopProductsProductDesc then the outcome would be the same as the first one.
CSS is all about specificity, if your selector is more specific than the last one used the properties would change. This is why you have to be careful if you are using specific selectors because your last option to alter the properties would be to use !important.
I hope this helps to clear things out.
After trying a few different styles, I think that personal preference (or a set standard if you have collaborators) is really the way to go. I prefer the second version, but the first one is also quite legible.
If you consider efficiency of what the browser has to do under the hood to render CSS styles, BEM-style for example, is usually the ultimate winner as it is the most lightweight for the browser. I use BEM for some layout/common elements.
In real life unless you are doing something seriously wrong, modern browsers and devices make this difference of CSS parsing and rendering somewhat negligible. But that is if you code everything well.
I've worked with spaghetti CSS codebases that could take minutes to render all SCSS (it was a huge codebase, but a few files were big bottlenecks).
It matters because of specificity. The first style rule will always override the second, regardless of where they both appear in the stylesheet, because it is more specific (basically it has more class selectors in it).
That said, the first rule is a nightmare from a maintainability perspective, for a number of reasons:
It makes code incredibly hard to read and understand
It's harder to override (as we have seen).
If you change the structure of the HTML, it will break
You can only reuse it if you mirror the structure of the HTML exactly.
It's also bad from a performance perspective. When browsers are matching an element to a style rule they read each selector right-to-left and keep going till they either find a match or can exclude the rule. Therefore, the more simple the selector is, the faster a match can be determined. If a selector consists of just a single class name, the browser can match the element with the style rule more quickly than if it has to search upwards in the DOM tree.
The second rule is better, but optimal would be something like the following:
.shopProductsProductDesc--warning {
color: red;
}
This solves all the problems above, and it's long enough that there's unlikely to be name clashes elsewhere, (though obviously not impossible).
In general, nesting selectors in CSS is bad practise, in my opinion, and the best CSS methodologies are those that have ways of avoiding this, e.g. BEM, CSS-in-JS.
According to my own experience, the second option is often best, not for direct technical reasons (in fine, it will perform the same), but rather for UX consistency and code maintenance.
The first option produce an "heavy" selector, which will be harder to override. It can be wanted, but it is often the sign of an overall messy CSS, because if everything is overconstraint, it is less easily reusable/extensible.
From my understanding of CSS and frontend reusable components, you would always only need two levels.
The style of your warning component (no size, no margin, size depends on where you will display it, and margin is position, only internal design here):
.warning {
//Your design here
font-size: 1.5rem;
font-weight: bold;
color: orange;
}
And the positionining and variants inside containers:
.container > .warning {
//This is an example.
position: absolute;
right: 0;
border: solid 1px red;
}
Having long CSS selectors will make things more complex, hard to follow for your teammates, and hard to override because you will probably need a longer CSS selector, and it never ends. Plus, you will get an heavier bundle at the end.
If you want an efficient UX, the UI shouldn't be that different everywhere, so you should not need to have that many variants of the same component. Otherwise, maybe you need multiple different components, but you certainly want a simple and efficient UX, and that often goes with not so much visual concepts, so you must avoid tons of variants.
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
I have following snippet
.global-oxygen-font{
font-family: $font-oxygen;
font-size: 16px;
line-height: 31px;
letter-spacing: 0.32px;
}
And I am extending it whenever it is used like this
line 100. div{#extend .global-oxygen-font}
line 200. p{#extend .global-oxygen-font}
So as you can see among different sections, I am extending the font-snippet. But during a code review I was told that put that
div,p{
font-family: $font-oxygen;
font-size: 16px;
line-height: 31px;
letter-spacing: 0.32px;
}
on the line 100 itself. Extending global-oxygen-font would essentially copy the code those places. I was like, but div and p exists in line 100 and 200 for a reason, as they are in order of the structure of the markup. And if I make the change as suggested, it won't be good for maintenance. Whose approach is correct?
Extending global-oxygen-font would essentially copy the code those places
No, that's not how #extend works. Instead it works by adding div and p to the list of selectors for .global-oxygen-font. (Compile it and view the result to verify this yourself.)
Therefore, if pressed I would say you are right, they are wrong. Your approach clearly isolates the rules and then assigns them to p and div, and therefore I would say it is also more maintainable.
You might want to designate .global-oxygen-font as a virtual class (using % IIRC) so no rules are generated for it (unless you want to be able to use that class explicitly).
I'm curious, though, why you would apply these rules to all p and div elements. It would seem to be better to write the class explicitly on those elements. Or, since all the properties are inheritable, it could make sense to apply them at a higher level.
Another comment:
as they are in order of the structure of the markup
There is no particular need to order your CSS so as to match the structure of the markup.
At the end of the day, it is often not a good idea to push back against code reviewers. They may have their own point of view, which they are allowed to assert because they are more senior. For instance, they might not even like the entire idea of #extend, and there are legitimate reasons some people avoid it.
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
I read an article where it was recommended that we should ONLY use classes in our markup and only use ids when we need to refere to it from javascript (as it is easier to attach functions to ids)
At the moment I only use classes when I have more than one element that needs the similar style. However the article (which I THINK I read - but have no reference) stated that we should use classes throughout
I would do this:
<header id="banner"></header>
Where as the recommendation was :
<header class="banner"></header>
(even though the banner is only used once per page)
is this the new "good practice"?
Thanks
As far as I know you are correct, you should use classes when you need to style multiple elements and IDs when you are only styling a unique element.
I think you may have stumbled on an article about object oriented css. The basic idea is that you should think of the style as a sort of abstraction which is linked to your markup via classes. I find it to be a good technique for keeping things organized, but, as with all techniques, it's not a universal hard and fast rule. I see no problem with linking style to markup with ID's, as long as that makes the most sense.
It's what "makes sense" that is the real tricky thing to define.
ID Attribute, Definition and Usage
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.
Read more about it here!
CLASS Attribute, Definition and Usage
The class attribute specifies one or more classnames for an element.
The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.
Read more about it here!
So, you can style using either Id's your Class's, just knowing that the class can be re-utilized on other elements across your web page, the Id must always be unique.
The reason to tell that Class's are the best attribute to utilize to apply CSS is because you can have generic class names and use then a lot through your web page, thus simplifying and reducing the time spend coding :)
Simple example:
HTML
<div id="theUniqueID">
Hello!
</div>
<div id="theUniqueIDTwo">
Hello Again!
</div>
CSS
#theUniqueID {
font-size: 15px;
text-align: right;
}
#theUniqueIDTwo {
font-size: 15px;
text-align: right;
}
Can be reduced to:
#theUniqueID, #theUniqueIDTwo {
font-size: 15px;
text-align: right;
}
And can be generically utilized across the document like this:
.format_01 {
font-size: 15px;
text-align: right;
}
Having then the HTML like:
<div class="format_01">
Hello!
</div>
<div class="format_01">
Hello Again!
</div>
<div class="format_01">
Hello Again and Again!
</div>
Ps:
Sorry for the overkill answer, but this allows others with less knowledge to learn as well.
Basically you should use id for unique elements that means if you want to keep an element on the page that won't be appear on the page twice then you should use id and to style a group of elements with same style or to keep some elements in the same group you should use class.
But remember, you can also use class for a single a element but you can never use an id for more than one element on the page.
For example, getElementById or $('#idOfElement') (using jQuery) returns a single element but getElementsByClassName or $('.idOfElement') (using jQuery) returns an array of matched elements. So if you have more than one element on the page using same id then you'll get only the first element that have the id, so never use id for more than one element.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I am wondering which selector is better practice and why?
Sample HTML Code
<div class="main">
<div class="category">
<div class="product">
</div>
</div>
</div>
and we want to reach .product with CSS selectors:
.product
.main .category .product
div.main div.category div.product
I am comparing them to the following criteria:
Performance
Maintainability
Readability
We may assume that .product is unique throughout the page. We can have used id instead of class but in this case, we chose class attribute.
We may assume that .product is unique throughout the page.
Performance-wise the best would of course have been an ID selector but since you're using a class instead, .product would come second.
As for maintainability, readability and semantics (there's a bit more on performance as well)...
.product means
Find any elements that have a class product.
Very easy to understand, almost identical to an ID selector if you use this based on the above assumption.
I guess the only difference between using a class selector and an ID selector in this case is that an ID selector enforces uniqueness of this element, and not only because there just happens to be one such element. In other words, an ID selector acts on the knowledge that a document will only have one such unique element, while a class selector does not.
.main .category .product means
Find any elements that have a class product
which are contained in any elements that have a class category
which are contained in any elements that have a class main.
Browsers are tasked with checking the ancestry of these elements, which is redundant if you only have one .product. Many browser layout engines evaluate CSS selectors from right to left, similarly to how I translated the selector to English as above.
div.main div.category div.product means
Find only <div> elements that have a class product
which are contained in only <div> elements that have a class category
which are contained in only <div> elements that have a class main.
In addition with checking the hierarchy of elements, you expect a browser to only match a div with the class product. If you want to match any element of this class then this selector wouldn't work as intended.
If you're sure you will only have exactly one div with that class, and you want to only match that element, then you could use div.product instead, but .product still performs fractionally better.
I'm no guru but I can at least comment.
I think first way is easily the best:
it prevents the CSS from having to traverse the DOM tree to find an element,
if you edit any of the parent elements then you will have to edit the CSS selector. Readability: personal choice, some people may like the second, but most won't really mind
I always try to use the smallest selector possible, so I would just use .product (i.e. your first example). I think this also has performance benefits since the browser only has to find elements marked with that single class, rather than trying to find a matching parent first, then checking to find out if it has a descendant marked with that class, etc.
The only reason I generally have to use the other methods you mention is if:
I'm trying to add specific styling under a specific context. For example if I wanted to bold all internal links (under a .internal_link class), but wanted them to also be underlined if they appeared in a certain context.
I need to add specificity in order to force my rule to take effect.
Finally, if you're assuming that there will only be one element marked with the .product class, then you're probably better off using that as an ID rather than as a class.
All the three selectors have different meanings and should be used at different places as the need be.
Performance wise, the first should be the best, because we just need to travel the DOM once.
Readability wise also the second and the third selectors seem cumbersome and may be difficult to extend in future.
.product
.main .category .product
div.main div.category div.product
Using the above selectors are depending on how complicated your site is.
Ex.
If all these elements is use only ones. The first selector may be fit.
The second way is best practice if you were using this for multiple pages(ex. you have these elements for a set of products).
The 3rd way for me is unnecessary unless you have this class name in other HTML tags like span..
more tips: Mushu Tricks
The first way .product is the best and the most easiest. If you use the .product you need not go through the entire file to find what you are looking for. You can also use an ID selector without using a class.