Can you use an ID or class of a HTML element as an identifier for CSS? - html

I'm on my road trip roundabout of learning more coding languages. Never practiced HTML since HTML 4.01. But this is more of a CSS thing.
I was expecting, since I see H1 and P1 being a thing, so I try button1. Feel stupid, then think about using an ID as an identifier. I want to make one button on the left and the other on the right side.
I can't find anything on w3schools, and other sites. I feel like I'm wording everything wrong.

Yes, you can. Ensure the class name or ID are set to your elements:
<div class="my-div-class" id="my-div-id"></div>
And then in your stylesheet, you can access these using 'selectors'. Classes are selected with a preceding ., and IDs with a preceding #:
.my-div-class {
/* Some styles... */
}
#my-div-id {
/* Some styles... */
}
You can see all CSS selectors here from W3Schools: https://www.w3schools.com/cssref/css_selectors.php
Or here from MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

Related

CSS - what is the point of, when defining a rule, you to put the element and then the class, not just the class?

So, I was looking at a tut on youtube the other day, and this guy kept defining css rules with classes really weirdly, and I wondered if one of u guys could explain the necessity of it: here is the code:
ul.class li{
color:#fff
}
Why can't he just do:
.class{
color:#fff
}
Thank you for reading my question, I hope you understand what I am asking for.
Video: https://youtu.be/2wCpkOk2uCg
P.S - Sorry for the giganticly large title 😏
When you put the element before the class, CSS only applies the styles to the members of that class that are of that specific element.
For example, if you had .class applied to 3 headers and 3 paragraphs, writing p.class would only affect the paragraphs.
With ul.class you're saying "Apply this styles to all the ul's with this class. If you only use .class you're saying "Apply this styles to ANYTHING that has this class". It's very different. :)
I can think of at least two reasons to include the element name as well as the class:
Specificity, i.e., which CSS rule takes effect on a target element when multiple rules apply to to it. There is a specificity algorithm that determines which rule is applied when multiple rules are in competition. This awesome Specificity Calculator is a great tool to help you understand the algorithm. So, in short, including the element name and the class gives it additional weight.
Documentation in your CSS. I tend to include the element as well as the class, e.g. h1.customer-name, to self-document what type of element the rule is being applied to. When I see .customer-name without the element name, I am not totally confident in what type of HTML element it is. Doing this means I don't have to keep the HTML structure in my head or consult the HTML repeatedly while I work on CSS. But this is pretty dependent on one's approach to CSS as well as the tools used, so I'm not sure I would consider it a good idea across the board.
And one more, but not least important thing. If you adding the tag name before the class name (such as span.class{}), so you got more specific rule and it's have bigger priority (no matter in which order that rules writter in css file). For example, if you write two rules:
.class { color: red }
and
span.class { color: blue }
you will get a blue text as a result.

Is there a reason not to use a single non-nested class name as CSS selector?

If I have a container and a list of item, I might have the following HTML markup:
<div class="container food foodcontainer">
<ul class="list foodlist">
<li class="listitem fooditems"></li>
...
And I can style them two ways (assuming using plain CSS and not less/sass or any other helpers). First, like one normally would do:
.food { /* style */ }
.food .list { /* style */ }
.food .list .listitems { /* style */ }
Or, I can simply reference everything by a verbose, descriptive class name:
.foodcontainer { /* style */ }
.foodlist { /* style */ }
.fooditems { /* style */ }
No more cascading relationships! Is there a reason not to do this for everything (such that every element is referenced by a single class/id name)? I (and people working on the same codebase) simply do not find either to be that much better in readability; if anything, we find unique and direct names easier to grasp and also easier to search for.
There was an ancient article that generally recommended shorter, more unique selectors, for performance; in its more recent update, it's said that overall the performance has changed for the better. But how much better? Is the shorter way still faster?
.food .list { /* style */ } targets only elements with list class that are within an element with a class food.
.food > .list { /* style */ } targets only elments with list class that are direct children of elements with a class food.
.list { /* style */ } targets any elements with the class list, regardless of their parent elements.
Generally, if you want to make sure you're only targeting an element within a specific element and not any other elements that might have the same class, use the first or the second of the above, depending on your needs.
Of course, you could also give unique classes to them to avoid chaining them, but IMO there's just an unnecessary hassle of remembering which classes you've already in use. Also, I think it helps with readability, when you chain them instead of coming up with unique classes - then it's easier to see within which elements these rules apply.
I wouldn't worry too much about the performance with either of those - unless you have massive sites.
You can read about the CSS selectors here.
Well you could give a class to every element, but the point of the cascading relationships are to prevent having to give a class to every element.
For example:
a{ /* style link elements some way */ }
.some-div a { /* but in some-div they should look differently }
In this case you only have to set 1 class on the div. Else you would have had to give every link element a class in your html, which is kind of counterproductive.
Using relations you can be a lot more generic and avoid getting to the point where you end up with names like header-logo-nav-link-first. You would have to remember that class, but you would also have to write it in every element. Ever seen a footer with 50+ links? ;)
Also the more specific you are with your selectors the more priority your styling gets.
Very interesting question. Essentially, you have identified two dimensions to your class architecture. The first is the food dimension, which has a semantic meaning, and is particular to all things related to food. The second is the list dimension, which is a layout dimension, and is particular to all things related to lists and their layout.
This is a very clever way of breaking down classes. It helps prevent rules having to do with food from "leaking" into rules having to do with lists and vice versa. Your HTML becomes a clean orthogonal combination of classes from groups of classes with different meanings. In my mind, this is ideal. It follows a particular CSS design philosophy of combining smaller classes in different ways, which promotes re-use and improves readability. The alternative is "kitchen-sink" classes which are harder to re-use and harder to read. This will tempt you to use pre-processors with features like #extend, and things will go downhill quickly from there.
The technical term for defining singleton classes is "hyper-targeted". An example id Food__orange-disabled--listitem. If you go down this route, you will spend the rest of your life writing and rewriting these bizarre-looking class names. Every single change will require changes to both CSS and HTML. Proponents of this approach claim efficiency as one reason to adopt it, and this might have been an issue five years ago, but as you mentioned, today's browsers handle reasonable amounts of nested selectors without breaking a sweat.
I'm revisiting this question as I found newer and more recent articles and references.
In short, there should be little reason stopping one from using non-nested names. In fact, it might even help with both performance and maintainability.
BEM (and other similar naming schemes) tackles the maintainability issue.
And, class-centric styles help with performance.
I also want to add a few more explanations to why some of the reasons given in the other answers, or what I've seen being said else where, doesn't quite apply to argue against the case.
"This is not how CSS works."
It is true that CSS has nested relationship available, naturally as its name suggests, but that itself doesn't become the reason why we must or should use it.
"Nested relationship is easier to maintain."
This is only a "maybe" depending on the code style. Say, we have a style sheet like below:
a { /***/ }
.some-div a { /***/ }
.more-div a { /***/ }
And, we have a link somewhere in the template:
<div class="some-div ...
<div ...
<div class="some-other-div" ...
<a href="...
Now, when we look at the link in the template, we see a tag a with no classes. What styles does it have? Well, we have to go to the style sheet and search for a, and there will be many, many a's, and they can be nested arbitrarily deep.
This is just like "magic numbers" in other programming languages; the only difference is that instead of a number constant we have tag names. Searching for a single a is like searching for 3 in source code; we have to infer most information from the context.
And there is no way to do a quick search for the css selector because we don't know which parent in the ancestry tree is used in the style sheet. It could have been .some-div a or .some-div .some-other-div:last-child a.
Instead, if we classed the tag itself (e.g. <a class="some-div-link-class some-other-class" ...). It will just be a single search away.

CSS notation: the meaning of ">"

In my website, I have the following structure on some html page:
<html>
<head><!-- All the usual information here, including the link to the css file --></head>
<body>
<div id="splash">
<!-- The good stuff -->
</div><!--End of Splash-->
</body>
</html>
Now that #splash div only appears on that one html page, and I need the css affecting that page's html {} to be a little different. Is the below notation going to do what I need?
html>body#splash {/* CSS that only affects the html that contains div #splash */}
I think you're looking for a parent selector; sadly this doesn't exist in CSS, so you're out of luck.
This is, from what I understand, mostly for performance reasons -- Jonathan Snook's article goes into a little more detail.
It's either time to change your page generation so that a class or ID gets added to the html element on your "splash" page, or resort to JavaScript, such as the jQuery cssParentSelector library that arkanciscan mentions.
Since IDs are unique, you can just do:
#splash {
/* stuff */
}
About your question:
html>body#splash
Will not work; try
html>body #splash
The > is basically the same this as a space, but selects only direct children.
(I'm assuming you're trying to select #splash; that's how I read your question. If you want to select body if #splash exists, then... well, you can't.)
Like others have said, you can't do this is CSS... yet! In the next version of CSS you'll be able to add an exclamation point to any part of a compound selector to indicate which element of the selector your rules should apply to. This will be called a "subject" (http://www.w3.org/TR/selectors4/#subject)
If you want to use this today you can try this polyfill https://github.com/Idered/cssParentSelector
Child selectors are indicated by >: http://www.w3.org/TR/CSS2/selector.html#child-selectors
It means you are selecting a first-level descendent.
Your code needs this space:
html>body #splash
This reads: "Select the element with the id of splash that is a descendent of body which is a child of html."
Your code is this:
html>body#splash
Your current code reads: "Select the body element with the id of splash that is a child of html.
As has been said, this can't be done in current CSS.
But just to give you a suggestion: you could add a unique ID or a class to the HTML in question; if you know which one it is ahead of time, just add it statically; if not, you'll have to actually look (with JS) if there's a div like you describe in the body, you can't do it with CSS alone.

Multiple Font Sizes for h1 element via CSS

I need to display a company name so that the "main" part of the name appears on one line and is huge and the secondary part of the name is centered below it and smaller. Since it's not a slogan or "subtitle", I feel like it should all be in the same h1 element and, ideally, be transformed through pure CSS (meaning no spans or ems if it can be avoided.
Example:
<h1>Big Bill's Custom Auto Parts</h1>
should appear as:
Big Bill's
Custom Auto Parts
Is there a pure CSS way of doing this (even a pseudo-class not fully supported yet)?
Not possible, it seems to make more sense that you have two different headers and can be styled accordingly.
How would you possibly specify where changes happen without adding a <span> within the <h1>?
Is it permissible to include a new line in the heading itself? If so you can use the first-line selector like this:
HTML
<h1>Foo bar
baz</h1>
CSS
h1 {
font-size:1em;
white-space:pre;
}
h1:first-line {
font-size:3em;
}
The shortest solution to this without using extra headers is the use of a span element:
<h1><span>Big Bill's</span> Custom Auto Parts</h1>
CSS:
h1.span {
/* styling rules */
}
If you're fine with breaking the line with a <br/>, then you might accomplish this using the ::first-line pseudo-element.
You said you want to do it in pure CSS way, separating content and presentation. No addtional spans, no br. I understand it, but if you think about your problem, you want to create presentation rule based on content. Is that making sense? Isn't that mixing content with presentation you want to avoid?
I tried other stuff in this thread, but this finally worked.
<h3>Tutorials <span style="font-size:14px;">(2 of them)</span></h3>

Using element IDs/class names over other CSS selectors

To what extend should I be attempting to use other CSS selectors instead of element IDs/class names or vice versa.
For instance: body > header nav ul+ul { ... } when I could just do #socialnav { ... } to achieve the same thing.
Example HTML code being (obviously there are headers with child navs elsewhere in the code):
<header>
<nav>
<ul>...</ul>
<ul....</ul>
</nav>
</header>
What is the consensus on this? I mean, I find it manageable doing it using CSS selectors, but is there a disadvantage?
Your first guiding principal should be to keep the markup semantic. Your markup above is a great example of this - you're using header, nav, and ul tags in semantically meaningful ways.
Your second guiding principal should be to maintain separation of concerns (e.g., content and presentation). If adding a class names or id's to your markup does nothing for you semantically and you're able to craft CSS selectors w/out them, then you should avoid adding extra noise to the markup.
Sometimes, however, class names and id's are very useful (not just in CSS but also in JavaScript), so they have their place. Just don't resort to them if they're unneeded and are therefore adding unnecessary clutter to your markup.
It's up to your preferences.
I find it not wise to use body > header nav ul+ul, because a small change in your document structure, and you have to rewrite the CSS selector.
Use .classselectors and #id-selectors for elements which aren't an incredible important part of the main document, and use #one-special-item > ul > li > a:hover span to select the more specific elements.
Generally I try and avoid ID selectors in CSS.
I find it a lot easier to deal with classes than using IDs.
IDs can cause issues later on down the line if the markup is used in a Server-Side application, such as ASP.NET, where the IDs are rendered as something different to how they display in the markup.
However, ID selectors do take priority over class selectors:
http://jsfiddle.net/wcLrF/
You should write your stylesheets as rule sets for your site.
If you are writing a style which is you want to to work with a single specific piece of content, then it is good practice to reference that element's ID.
If you are writing a style which is part of your general site look and feel, then it should be written to reference tagnames and/or classes as much as possible.
There will be times when the actual html code is such that it becomes hard to follow those rules, but if you try to stick to that in general then you'll be okay. You may also need to bend your rules if you need to support older browsers (cough, IE, cough) that don't support all the CSS features that you'd normally want to use.
So yes, I would say that the way you've done it in the question is the recommended approach.
Using IDs and Classes as selectors is much faster than using normal css selectors. Some also argue that you should ONLY use classes because they encourage reusability in your stylesheets.
Here's a really good article about Object Oriented CSS: http://coding.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/