Using IDs in LESS - css

I've started using LESS recently and it's really convenient, and I have a question: as it's really convenient to place element inside the brackets to clarify the style structure, in .CSS file that's being generated I end up seeing things like this:
#second-block .side-menu #category .content{...}
Is this okay to have id elements inside other id elements, even though I use LESS?

Yes. It's ok to have id element inside other id elements.
The generated .css will work.
Personally, I like to use as few id elements in my code as possible. The reasoning behind this, is how some browsers don't like it when you have multiple instances of the same id on the page. I find that using classes is more flexible.
Here's a relevant stack overflow question that mentions on ids vs. classes:
Is there any pros and cons if i use always CSS Class instead CSS ID for everything?

Related

Using nth-child or creating new classes in CSS?

I've just started my first project which is building an admin panel. My task is to create HTML and CSS - sort of a base of design to process further to the back-end developers.
I was asked to keep CSS simple and classes as descriptive as possible ( could be long ) and to use Bootstrap.
To avoid creating unnecessary classes which could be used once or twice I decided to go with :nth-child since I thought giving new class to each column is too much. Additionally I created few base classes that might be used for adding 0px padding and margin.
Unfortunately, as I was writing more and more code I've noticed that some CSS code looks like this:
.print-history-advanced-search > [class*='col-']:nth-child(5) > .form-group > .form-horizontal > .form-group > [class*='col-']:first-child
And it is not a single line.
Additionally, I've noticed that sometimes that when I am making a new class and it has lots of parent elements, I cannot write the CSS selector by its own, but I need to state the parents of the this particular element and put the class at the end, which does not make sense.
Is there any solution I could use to avoid creating classes that are simply used in one or two divs, but also make the CSS code less chaotic and avoid very long names? Or maybe I should just give up on children and nesting and work with just classes?
Thank you for your help!
Have a nice day!
If you want to write good CSS, then I'd suggest the BEM model is a good route to go down.
The essentials are;
No element/selector heirachy
No use of elements in selectors
Class based styles only
BEM stands for Block, Element, Modifier - which is how your class names are formed. Borrowing an example from their site;
.form { }
.form--theme-xmas { }
.form--simple { }
.form__input { }
.form__submit { }
.form__submit--disabled { }
<form class="form form--theme-xmas form--simple">
<input class="form__input" type="text" />
<input
class="form__submit form__submit--disabled"
type="submit" />
</form>
You can see there's a form Block, and then a form__input and form__submit Element, and then a form__submit--disabled Modifier.
Depending on your needs I would recommend using css preprocessors like SASS,LESS.
You’ll find that as a website grows, you’ll develop a pretty long, scrolling list of various elements and CSS rules. Some of the rules might overlap or override each other eventually (in that case, usually the more specific rule will win).
You can end up with a lot more code than you expected, especially considering the different variations of a rule you need for different browsers and screen sizes.
There are many ways to refactor your CSS code to make it easier to navigate and use. Some of the easiest methods are the most effective and have the most mileage. Here are some of the quickest ones:
Keep your spacing uniform: Maintain the same spacing between rules
and within declarations throughout your file so that it’s easier to
read.
Use semantic or “familiar” class/id names: Instead of using a class
name like “bottom_menu”, try using the semantic tag “footer”. Or
when you have an image in your “contact” section, make sure you’re
using a class on your image like “contact_image”
Keep it DRY (Don’t Repeat Yourself): Ideally you want to repeat as
little of your code as possible. Do you find the declaration
“background-color: #000″ repeated throughout your CSS file? Consider
typing it once and instead, using multiple selectors on the one
declaration.
Put your tidiness to the test with these tools: Run your CSS through
CSS Lint or W3C—these will help to parse your CSS file correctly,
and highlight problem areas. Your web browser’s developer tools are
also extremely useful for pinpointing specific elements on your
website and using the area as a sandbox to experiment with different
styles and positioning.
Have a look here for more info

Is it improper to use an ID as a CSS selector? [duplicate]

This question already has answers here:
What is the difference between id and class in CSS, and when should I use them? [duplicate]
(15 answers)
Closed 7 years ago.
So I often use a website LiveWeave.com to test HTML, CSS, and JavaScript code that I've written. It has a syntax checker, and whenever I use an ID as a selector in the CSS section, it says that it is improper to use an ID as a selector.
I have demonstrated it in this Weaver. To the right of line three in the CSS window is a yellow icon, which, when hovered over, says that it is improper to use IDs as a selector. I was under the impression that that is specifically for the purpose of being used as a selector for a single DOM element, as opposed to classes, which are designed to be applied to multiple DOM elements.
Am I wrong? IS it improper to use an ID as a selector?
The only other instance I can think of an ID being used is for JavaScript document.getElementById(), and similar functions. What is the proper use of an ID?
Note that I am NOT asking the difference between an ID and a Class, but rather whether it is proper to use an ID as a selector.
Using an ID is the most efficient way of selecting a DOM node in both CSS and Javascript. I personally like to use classes for all repeated items and ids for unique items, or unique configurations of repeated modules. There are many CSS patterns, I use a style called BEM (Block, Element, Modifier as seen here) which is a class based naming convention. Look at your favorite websites, right click or inspect. You will find that there is no one right answer to your question, only many right answers.
May I also say that both exist in the standard for a reason and serve a purpose depending on your applications needs.
Below is the order of efficiency for selectors. IDs are the most efficient and pseudo classes and pseudo elements are the least efficient.
id (#myid)
class (.myclass)
tag (div, h1, p)
adjacent sibling (h1 + p)
child (ul > li)
descendent (li a)
universal (*)
attribute (a[rel=”external”])
pseudo-class and pseudo element (a:hover, li:first)
See here...
It is not improper to use ID's as selectors, so long as the ID being used corresponds to only one element in the DOM (document object model).
If you'd like a selector that is multi-purpose, and able to be applied to multiple elements in the DOM, use a class. Although I'm sure you knew that.
The main reason ID's are frowned upon by some CSS developers, and full stack designers, is simply because they aren't as versatile and they have a higher specificity than classes, which can either help or hinder development (based on CSS knowledge).
For more information on CSS specificity, read here: https://css-tricks.com/specifics-on-css-specificity/
It's valid, it's just considered bad practice by some developers because it can make it difficult to maintain your CSS if you're not disciplined about it. I'm no expert on CSS but I'm pretty sure it's all to do with #'s having a really high specificity rating and if you have them dotted around your CSS files it makes it difficult to manage the cascade i.e. inheritance of style rules. So it's considered best by some to use IDs only for referencing elements in your JavaScript.
I've actually heard this argument before.
Some people push the idea of using solely classes for pure css stuff and keeping id for javascript and other id specific functionality.
It would seem that website follows that ideology, so they are trying to get their users to adopt it. I'm not sure if it is yet best practice to keep id out of css
You can decide for yourself whether an id is worth using, when you could just use a class instead.
If you used an ID as a selector and your using it in your Javascript too then you could make situation where if you decide to rename it then you've created a dependency that wouldn't be there if you had used a class name in your CSS.
Also, though using the ID is faster, it isn't faster if you then use #text a - since CSS reads right to left and has to check all the anchor elements first and then find the one with the ID of #text.
This also means the style isn't reusable and you can't use multiple classes either.
So I think the answer really is, based on all the pros and cons of using an ID as the selector, the best practice to keep you out of possible future problems is to not do it. Of course, this all really depends on how you code, the scope of the project and how many other people are working in the project. It's not against the rules, just not really best practice due to possible issues you might be building in that could bite you later.
On top of what has already been mentioned, even in CSS, ID's can be useful depending on what is the structural design.
For example; if every page in your website requires a header and a footer, I don't see why it would not be useful to make it an id.
What is wrong with doing:
#header {}
#footer {}
If you know for sure that your page has only one header and one footer, I don't see the point in using a class.
Mentioning the id is very specific and the page structure is undubious in this case.
Moreover, I also don't see what is wrong by doing something for example like:
.menu{}
#header .menu li{}
#footer .menu li{}
To add specific styling depending on the page segment. Seems very legit to me.
Ultimately, I even think that using ID's to indicate page sections might be more beneficial by ´knowing´ that they are unique (although they might be recurrent across different pages).
Reading an id in a CSS file should give the CSS designer the benefit of immediately knowing what page segment the following css rules are referring to.
A sheet with only classes would in that case seem less clear than using ID's imo.

Is it okay to use css classnames as an id for a module or widget? [closed]

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 read an interesting post on using a css classname instead of the id attribute for identifying modules or widgets. The css classname could be prefixed with a hash or underscore, to indicate that the classname is used as an id. The reason for this being, that ids can only be used once per webpage whereas a module or widget could appear multiple times.
Simple Example
Instead of using ids such as
<div id="currencyConverter1" class="foo">EUR/USD</div>
<div id="currencyConverter2" class="foo">GB/USD</div>
prefixed classnames are used
<div class="#currencyConverter foo">EUR/USD</div>
<div class="#currencyConverter foo">GB/USD</div>
In the article it suggests, that an underscore could be used instead of a hash, because hashes need to be escaped.
I quite like this idea, but I'm not sure if this is good practice or has any drawbacks. What is the general opinion on this?
It doesn't get simpler than this: does it uniquely identify an element within a document tree now and forever? Use an ID. If not, use a class name.
Remember that IDs and classes are properties pertaining to each element, not a group of elements collectively. Using "identifier" to mean "identifying a group of elements" is futile; that's why you have class names instead, to classify those elements as being related in some manner.
If you're "identifying" elements that are members of a specific widget or module, you have free reign to add a class name to each element representing that widget or module, and select it in addition to the element's class:
<div class="my-module foo">.my-module.foo</div>
<div class="my-module bar">.my-module.bar</div>
Or, if specificity is such a huge issue that you can't even afford to stack another class selector to your rules, prefix the element's class name with the name of that module and select it.
<div class="my-module-foo">.my-module-foo</div>
<div class="my-module-bar">.my-module-bar</div>
If that's the question, then yes, it's perfectly legitimate — as I've mentioned, that's the whole point of class names and selectors.
But there are no legitimate benefits to making a class selector "look like" an ID selector without functioning like one. What it does cause, on the other hand, is needless confusion, especially for other authors who may not know better. If you want to avoid ID selectors like the plague, fine, leave them alone; nobody's forcing you to use them. But if you want to uniquely identify singular elements, then you may want to remember that CSS already provides a feature for that to complement the id attribute in HTML, known as the ID selector. There's no need to hack other parts of the selector syntax to emulate some other feature that's already readily available to you and has been since the very beginning.
Incidentally, if you're running into specificity issues with your CSS rules, then it's your CSS rules that need refactoring, not your markup. Hacking your markup to accommodate your style rules only leads to further trouble, at least in my experience. (I understand the irony in saying this given that hashes are allowed in identifiers starting with HTML5.)
Its mostly driven by your own, personal taste. there are a lot of opinions and articles on this topic, even complete books were written.
I suggest the following:
SMACSS
OOCSS
MVCSS
All of them are mentioning a more-or-less similiar naming convention for CSS, while also saying that these are just rules of thumb, not dogmas.
personally, i follow that approach:
.modName // module
.modName__sub // an object or sub-module
.modName__sub--modifier // a modifier
A similiar structure is used for example by InuitCSS
If you want to use classnames as unique identifiers, than just do it, there is nothing wrong about that. Further, it is future proof in case that you wish to use it as a "standard" class. However, i would shirk that hash for obvious reasons.
Not sure what your modules or widgets are for (wordpress?) but the methodology I choose to use when coding is this:
1: If it is DOM element that has a specific function that I know will only appear once on the page, then I use an ID (things like #main_navigation, #global_header).
2: The DOM element is used for styling purposes (CSS) then I use class names. I keep class names as descriptive of what the DOM element is doing as I can. I don't use vauge names like .blue_text (explained below).
3: I need to attach some sort of information to the DOM element that is kind of awkward and doesn't fit this scheme, then I use custom HTML data attributes. For example, if I create a backend for a site and a user can pick a background color for a div, instead of putting .user_selected_background_color_class as a class in the div I will instead write data="user_selected_color". This is a kind of lame example, but I just built something where a user can select a bunch of images to be in gallery mode or slideshow mode and I used data attributes to determine how the container div should be styled.

CSS Best-Practice: Selectors or Classes / IDs? [closed]

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 10 years ago.
What is the truly a best-practice in CSS: Using IDs and Classes or Selectors?
I have a stylesheet that is required by PHP once a form is submitted to style the results / successful-submission page and I was wondering what is a best-practise in CSS to use IDs and Classes or to use Selectors ?
Basically classes should be used for common page objects that may or could be repeated. ID's should only be used when there is a unique element on a page that you will not have anywhere else on the page.
One way to explain this would be:
ID = A person's Identification (ID) is unique to one person.
Class = There are many people in a class.
There are no browser defaults for CLASSES and ID's
Adding a class name or ID to an element does nothing to that element by default.
This is something that snagged me as a beginner. You are working on one site and figure out that applying a particular class name fixes a problem you are having. Then you jump over to another site with the same problem and try to fix it with that same class name thinking the class name itself has some magical property to it only to find out it didn't work.
Classes and ID's don't have any styling information to them all by themselves. They require CSS to target them and apply styling.
ID's have special browser functionality
Classes have no special abilities in the browser, but ID's do have one very important trick up their sleeve. This is the "hash value" in the URL. If you have a URL like http://yourdomain.com#comments, the browser will attempt to locate the element with an ID of "comments" and will automatically scroll the page to show that element. It is important to note here that the browser will scroll whatever element it needs to in order to show that element, so if you did something special like a scrollable DIV area within your regular body, that div will be scrolled too.
This is an important reason right here why having ID's be absolutely unique is important. So your browser knows where to scroll!
Elements can have BOTH
There is nothing stopping you from having both an ID and a Class on a single element. In fact, it is often a very good idea. Take for example the default markup for a WordPress comment list item:
<li id="comment-27299" class="item">
It has a class applied to it that you may want for styling all comments on the page, but it also has a unique ID value (dynamically generated by WordPress, nicely enough). This ID value is useful for direct linking. Now I can link directly do a particular comment on a particular page easily.
CAUTION: Be aware, Javascript does care
JavaScript people are already probably more in tune with the differences between classes and ID's. JavaScript depends on there being only one page element with any particular, or else the commonly used getElementById function wouldn't be dependable. For those familiar with jQuery, you know how easy it is to add and remove classes to page elements. It is a native and built in function of jQuery. Notice how no such function exists for ID's. It is not the responsibility of JavaScript to manipulate these values, it would cause more problems than it would be worth.
If you don't need them, don't use them
As you can see, classes and ID's are very important and we rely on them every day to do the styling and page manipulation that we need to do. However, you should use them judiciously and semantically.
This means avoiding things like this:
CSS-Tricks.com
We already know this element is a link, it's an anchor element! No particular need here to apply a class, as we can already apply styling via its tag.
Also avoid this:
<div id="right-col">
ID is appropriately used here as the page will likely only have a single right column, but the name is inappropriate. Try and describe the context of the element, not where it is or what it looks like. An ID here of "sidebar" would be more appropriate.
The choice will depend on how your HTML is structured. If a certain style is used more than once, use classes. If a style used only for a specific tag, use IDs. Regarding the selectors, the trick is to keep them as short as possible.
Classes should be used when you're styling multiple elements on a page or across your website such as all the p tags. ID's should only be used once per page to style general layout such as a wrapper, container etc.
Use IDs for unique elements and use classes to apply styles more generally.
Forms should use IDs because generally they are all unique. Anything within that can use classes and you can combine the ID and class to specifically target them if need be.
HTML:
<form id="member-signup">
<div class="align-left">
<input type="text" class="large" />
</div>
</form>
CSS:
#member-signup {
width:600px;
float:left
}
.align-left {
text-align:left;
float:left;
}
input.large {
width:300px;
}
#member-signup input.large {
width:450px;
}
With the semantics of HTML5, selectors are the natural way to go initially for layout based styling.
Classes are great for adding flair to elements and minimal "logic flags" for templates.
Save ids for your special elements like scrim overlays, page names and wrappers.
There should only be one instance of an id on a page, ever; which you should always keep in mind when you are writing code generated markup. Multiple ids per page can lead to some nasty bugs later on; simple bugs, but sometimes difficult to discover.

CSS: are class and id interchangeable?

I know others have asked about using class and id in CSS files, such as
Div: Class vs Id
So I'm aware of the semantic and syntactic differences between class and id: that id should be used for elements that are used only once and class should be used for elements that share attributes in common.
But this isn't a hard-and-fast rule, is it? What's the harm in using an id for more than one element? Or using a class for only one? After all, isn't "one element" just a set (class) with only one thing in it?
Will the browser's CSS interpreter throw an error if I break the rules? I haven't seen it happen.
So why do we have both id and class? Why not just one one or the other and call it good?
duplicate IDs are not allowed; though your browser may or may not care, the notion makes no sense - how can it be an ID if there are duplicates? ;-)
CSS won't complain if you do it but Javascript sure will if you want to grab one element by its id.
The real answer is that there is a semantic difference between an identifier for one and only one object and an identifier that can apply to multiple objects. While you can break the rules it is best not to.
There is also one other distinction between the two, an (X)HTML element allows more than one class to be applied like this:
<div class="foo bar"></div>
You can't do that with ids.
In answer to the question 'why do we use both classes and ids for CSS, when you're allowed to have a single instance of a class?', look at it this way.
We don't need IDs for CSS. We could just use single instances of classes.
But we need IDs for JavaScript. So, why not use them in CSS too?
Imagine a world in which IDs were there, but only used for JavaScript.
You'd have to code like this:
<div id="wrapper" class="wrapper">
<div id="nav" class="nav">
</div>
</div>
and so on.
CSS is not the problem (you just define styles in there), but the document validity.
An id is meant to uniquely identify an element (for whatever purposes you will be using it) so when you have two elements with the same ID no good things will come.
Remember, the "id" attribute is not meant specifically for CSS styling (not as a class, at least), but for other things - specially JavaScript!
I for one wouldn't use "document.getElementById()" if i didn't know what i was going to get in return...
If you have only one element in a given class you're not doing any harm. The difference is only semantic in this case, as all you are doing is simulating an id. However, if you have more than one element with the same id, you'll have problems with page validation, CSS positioning, and Javascript references to that id. It's best to use id and class attributes as they were intended, for the greatest flexibility in styling your page. Remember, you can have an element with a unique id and have it belong to one or more classes at the same time.
IDs are usefull for elements you know will be unique to each page.
For instance:
a menu (#menu)
the central column where you'll put your main content (#content)
the right column where you put external links (#external-links)
You will probably need very specific rules for these elements (precise, non-relative width & position).
Now each of these elements will contain several instances of a certain type of object:
menu will contain .menu-items
central will contain .articles
external-links will contain .external-link
This subelements are not unique but their layout properties are... thus the use of classes.
And each of these subelements probably have subclasses (like .featured-article) or even some may have an ID (#current-menu-item).
Of course, you can always use classes inplace of IDs but I think using IDs makes it clear about which elements are unique and which are not. Beside, I prefer to have less space-separated names in my class attributes for them to be reasonably readable.
There are many things to say about it. You already know about the semantic meaning of id an class, so I just talk about one case - excluding javascript - when to use an id makes difference: you can refer to elements with an id to navigate inside the page with anchors or from external links: you can link a specific element of an html document with <a href="http://www.site.com/home.html#news> if you want to go directly to the element with id="news". Obviously, you can't to it with classes, because classes are not unique. So, for this and other reasons, is important to have an attribute that identifies an element inside a document.

Resources