Best practice for matching nested elements in CSS [closed] - 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 7 years ago.
Improve this question
I did some research and couldn't definitively find the answer to whether its best practice to use a class selector or tag selector for a nested element. Say I have the HTML:
<ul>
<li class="list-item-content" >
<img src="/images/flags/fr.png" class="country-flag">
</li>
</ul>
I could write :
.list-item-content img{
vertical-align: middle;
}
Or
.list-item-content .country-flag{
vertical-align: middle;
}
Which is best practice? Since the browser matches rules right to left, I would assume the second way is better as with the first way the browser with first match ALL images, then check the parents....

For more specific css you have to use both like following :-
.list-item-content img.country-flag{
vertical-align: middle;
}
It will define more clear nesting structure.

Personally, I think using two classes in the rule like $('.class1 .class2') matches more efficiently and is better practice. And maybe rarely need 3 classes.
In case you are very sure a class is unique, then $('.class1') maybe enough.

It depends of the complexity of your project and preference of your team.
In term of performance, selecting nesting items with something like this
.list-item-content .country-flag{}
which translage to
select .country-flag elements descendant of .list-item-content element
could have a performance penalty on large project (DOM) or in device with limited capabilities (like smart tvs or old mobile devices).
In order to mitigate this risk you can try to use a name convention which will help you to prevent selecting nesting element in an expensive way.
One of the methodology is called BEM.
Briefly the convention is as follow:
.block represents the higher level of an abstraction or component.
.block__element represents a descendent of .block that helps form .block as a whole.
.block--modifier represents a different state or version of .block.
So you HTML could be rewritten like this:
<div class="componenet">
<ul>
<li class="componenet__list" >
<img src="/images/flags/fr.png" class="componenet__list-flag">
</li>
</ul>
</div>
in this case you can select directing your class
.componenet__list-flag {}
More info here:
http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/

Most of the time you will not trying to match all img therefore 2nd convention is prefered
.list-item-content .country-flag{
vertical-align: middle;
}
This is another good practice by Harsh Sanghani as well.
.list-item-content img.country-flag{
vertical-align: middle;
}

Related

In HTML5+CSS, is <nav class="nav"> redundant? [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 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.

Why CSS does not support function-like constructions? [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 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.

Similarities between HTML class and OO class [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 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.

Should I be using only classes for the css styles? [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 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.

Anyone Using Nicole Sullivan's Object Oriented CSS Framework? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
Edit: Due to an excellent comment by Kobi pointing to this StackOverflow Question, I have amended the question below:
Has anyone out there tried out Nicole Sullivan's Object-Oriented CSS framework or one of their own? If so, what were the advantages/disadvantages?
Are there any production sites using the framework Object-Oriented CSS?
I use both OOCSS and normal CSS in most of my stylesheets. I don't think that it makes sense to use OOCSS for styling of typography, but for things like columns, boxes and buttons, I think that it does make sense and it can really help to (in my opinion) make the code simpler.
Using a rather contrived (and terrible - classes should describe function, not form) example:
Using OOCSS
a.button {display: block; background-color: red;}
a.border {border: 1px solid orange;}
<a class="button border" href="#">My bordered button</a>
<a class="button" href="#">My normal button</a>
Using normal CSS
a.button_and_border {display: block; background-color: red; border: 1px solid orange;}
a.button_no_border {display: block; background-color: red;}
<a class="button_and_border" href="#">My bordered button</a>
<a class="button_no_border" href="#">My normal button</a>
As you can see, there's less CSS in the OO example, which I personally find easier to read. But I suppose at the end of the day, it's all down to personal preference and coding style :)
The OOCSS framework doesn't solve some of the problems defined by its own principles. OOCSS still contains redundancy and by moving the composition of components into the DOM, its coupling content back to the presentation.
OOCSS does make some good design decisions that should encourage users to maintain their CSS in a consistent fashion. This is a good thing. But the lack of documentation supplied with it means you'd have to reverse engineer it should it not quite fit your needs. This process wouldn't be reliable so you could end up back where you started... with messy CSS.
you shouldnt specify the tag in the oocss, its one of the pitfalls that she presented, so you can use the .button on any other tag and then extend that new tag..eg.
<button class="button">works on this</button>
<a class="button">works on this also</a>
<input type="submit" class="button" value="and this too"/>
specifying a.button in the css means you'll have to repeat it in the css again if u want to use it on another tag..
the main point is so that you dont repeat your styles and avoid redundancy..
you should download her examples on github
I am using it and loving it. The college I am employed uses rich intranet web applications that use a list {} object that I created. It arranges links horizontally and vertically, but has "extending classes" (skins) to convert them into header bars, menus, tool bars, tabs, accordions, and button groups. The List {} object contains no colors or borders, just a clearfix and a few modifiers. The actually appearance is stored in separate classes. I also use preprocessors to
I would make 3 suggestions if you go down this route.
Use the B.E.M (block / element / modifier) naming conventions
Think basic lego blocks and use use classes to extend them.
Use LESS or SASS to separate out the appearance

Resources