I'm trying to apply my poor knowledge of CSS to a little toy project I have going, and it's annoying me endlessly that I have to declare column widths in my HTML markup.
Is there a way so that I can, instead of
<div class="grid_4"></div>
use something like
<div id="leftNav"></div>
and in the stylesheet apply the grid_4 class to the element with id leftNav?
In my mind it would look something like this
#leftNav {
apply-class: grid_4;
}
Is there anything like that available in CSS?
Not in regular CSS, no.
There are CSS preprocessors though, which create a new mini-language which then gets processed into regular CSS, which add those and more features. See less, Sass.
Related
Let's say I have a structure like this:
<article class="product">
<header class="product__header">
<h1 class="product__headline">Headline</h1>
<img class="product__hero" src="" alt="">
</header>
<p class="product__description">Content</p>
</article>
As the Block element article brings all the styles it needs by default, it actually doesn't have any CSS. So I'm not defining it in the CSS like this, because it only clutters the styles:
.product { }
But I'm unsure about the HTML. Should it be
<article class="product"></article>
… anyways or simply …
<article></article>
… as there are no styles attached?
What is the right thing to do when usin BEM?
As I understand it, the idea with BEM is to use a standard and have a markup ready for any present or future CSS, so you would always include the class, even if you don't use it right now.
Another good reason is that the parent class improves readability and order for anyone looking at the markup. I would even suggest you to include the class in your CSS and left it blank, functioning almost like a subtitle, with the potential to be useful later on.
Finally, BEM recommends against nesting elements in the stylesheet, which means preferring the use of classes even in the smallest children (like a strong tag inside a p). Seems natural, then, to have a class in the parent as well.
Keep the class to keep your independence. Future changes might require you style . This approach has several advantages:
In 2 months you'll still be able to determine the module components and structure without further ado
You and everybody else will know that is the component container even if you add further wrapping elements in-between.
You might be able to alter the layout without touching the HTML
No dependency between HTML semantics and layout.
All present structure is mirrored into the layout so you can see all variants and elements in the CSS. Get things out of your head
Finally, I agree with you that CSS clutter isn't nice but it could be useful, especially when you're working on a larger codebase with a larger team where you need to rely on standards.
On your parser/IDE: it will probably be configurable to ignore such entries. Your build process should be able to remove these empty selectors so it doesn't make its way into production CSS.
I have come across a similar scenario, If you are following BEM, then keep that class in the article element, since it will help in maintenance(such as removing unused styles, better understand markup).
for example(in product.scss):-
.product {
&__header {
font-size: 1.7rem
// etc...
}
}
Hope this helps. Happy coding....
Note:- Depends upon your markup, you can hoist block element class responsibility to the parent element and updated child class with new parent class.(eg:- .root__prdHeader)
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
What is the best way of defining general non-block-specific styles throughout the site?
For example:
html
<div class="intro">
<p class="intro__text">foo</p>
</div>
<div class="profile">
<p class="profile__text">bar</p>
</div>
sass/css
.intro__text {
}
.profile__text {
}
.text {
margin-bottom: 0.5em;
}
If I wanted the text to be styled the same, would I (given I am using a pre-processor) #extend .text into the .intro__text and .profile__text classes, or just have all paragraphs throughout the site have a class of text?
Both those solutions seem slightly incorrect to me.
If I have a very common style, it feels like I'm going to be duplicating a lot of styles throughout my rendered css (bumping up the filesize) but having a class of text repeated all throughout my markup seems unnecessarily verbose and untidy.
Is there a best practice for this situation?
I can't say that there is the best way to do it. It depends on the structure of your project and what style your prefer. Both approaches are used in mostly code.
If you like to manage styles through css files - write #extend. However in case you want an element without common style you have to create a modifier for the el. For example - .profile__text--reset.
If you want declare common styles, your class list with common classes may become too long. But it is more clear and specific. And you have a possibility to manage it via javascript.
One improvement for this code is that it is better to use helpers with modifiers. For example, instead of simple .text use .text--sm or .text--m-sm. Or if you want only margin - .m-sm. But it is up to you.
You have several options:
Preprocessor (Sass/LESS/etc) mixins + clean-css/postcss cleaner — this way is simple and powerful, but not flexible, since it's not useful for dynamic landing pages, SPA, etc.;
Element of outer block mix (BEM/runtime mixin): class="intro__text grid__text" — in that way you just splitting manually visual and positioning styles and use their classes together;
Other block mix: class="intro__text paragraph paragraph--valuable" — almost like the previous variant but without linking to the abstract grid block, the best and the most flexible way (IMHO).
NB: Also you can extend BEM mixes with modifiers even in runtime, it's VERY powerful tool.
NB2: If you don't need dynamic web pages, you can freely use sass mixins. Personally I don't use sass/less mixins, only global variables for colors, grid, gaps, etc used in my own classes.
I try to code CSS in "Help Class Style" today and many developers on Twitter said it was a bad practice.
Here is an example:
<span class="et-margin-top-30 et-width-400 et-display-inline">
<p class="et-common-frame-shadow et-inner-img-shadow">
<img class="et-common-frame-img" src="img3.jpg"/>
</p>
<h3 class="et-margin-top-10 et-fontsize-26 et-fontweight-bold">foo</h3>
<p class="et-margin-top-10">bar</p>
</span>
Why is it a bad practice? When should we use a helper class such as .clear?
The idea of styling via CSS is separation between content and styling. Your content is in HTML and CSS provides the information on how that should be visually displayed. If you want to change one, you can do so without changing the other.
By naming your classes et-margin-top-30, you're putting the styling information back into your HTML. You may as well write style="margin-top: 30px". Because if you decide that that element should have a 50 pixel margin after all, you need to change both the CSS and the HTML. That's why it's bad style.
You should rather name your HTML elements by their function (e.g. class="headline", or class="call-to-action"), then describe in your CSS how that headline or that call-to-action should be styled. If you want to change that later, you can do so by simply editing your CSS, the HTML doesn't need to change.
Not to mention that if you're using Javascript to manipulate elements, using document.getElementsByClassName('et-margin-top-30') a) makes it very hard to understand the meaning of your scripts and HTML structure and b) requires that you modify your HTML, CSS and Javascript every time you want to tweak the visual appearance of an element. Using descriptive class names becomes doubly important then.
What you are trying to do there looks horrible. It looks like you have a class for all different styling attributes. Not only will it make your HTML unreadable, but it will also enlarge the file size.
What if an element has 15 styles "attached" to it. Will it have 15 classes?
I also think this will only make this slower to render (this is just something I just made up and for which I have no proof), because it has to look up all those classes.
I don't see any difference in doing <p style="color: red;"></p>.
I am first time poster. A question. How do a make a css declaration that only works within one DIV, but, not overwriting the global css? I want to jQuery loading a page into a DIV, however, the page's CSS changed my own site's CSS. I don't want that. Also I can't just take out CSS because I want them looked as intended from the source.
Basically we are going to load an external HTML with its CSS style applied locally ONLY without it changing the style elsewhere. The external HTML is not using inline CSS since we don't have control over it. They are applied to class values or even all element type. We don't want their CSS declaration modifying our own existing CSS outside of the DIV container.
Is this even possible?
Thank You?
If I understand your question correct you would place an id in the div <div id="mystyle"> content </div>. In your CSS you would write #mystyle p { color:red; }. which have no effect on global paragraphs outside the "mystyle" div.
I guess you are asking how to apply an external stylesheet to just one div. There is no way to do this using just CSS. You might be able to emulate this using JavaScript, but it's going to take quite a bit of work. Here's an outline of how you might go about doing this:
Grab the stylesheet filename from the loaded HTML and then get the contents of the CSS file via AJAX.
Somehow parse the CSS and prefix your div ID to each CSS rule, so that it applies only within your div.
Inject the modified stylesheet as inline text into the loaded HTML.
Steps 1 and 3 are relatively simple, step 2 requires a CSS parser written in JavaScript. (There seems to be one available here although there is no documentation.)