Drupal Allow a Custom Css Client Upload

Note: Changes to Drupal coding standards are proposed and discussed in issues in the Coding Standards project.

Note: This document aims to utilise emerging all-time-practices for CSS to Drupal 8/ix. As we implement these ideas in Drupal 8, this document may need to be updated.

Skip to best practices

Goals

The goals of good CSS should not be and then unlike from those of good software technology. Well-architected CSS, similar PHP or JavaScript, should be:

ane. Predictable

CSS throughout Drupal core and contributed modules should be consistent and understandable. Changes should do what you would expect without side-effects.

two. Reusable

CSS rules should be abstruse and decoupled enough that yous tin can build new components quickly from existing parts without having to recode patterns and problems you lot've already solved. – Philip Walton, CSS Architecture

3. Maintainable

As new components and features are needed, it should exist easy to add, alter and extend CSS without breaking (or refactoring) existing styles.

iv. Scalable

CSS should be like shooting fish in a barrel to manage for a single programmer or for large, distributed teams (like Drupal's).

The Component

Components are the discrete, purpose-built visual elements that make up the UI of a site or app. Components consist of HTML, CSS, and often – but not always – JavaScript. They are our navbars, dialogs, buttons and carousels. Components can be unproblematic (such as icon containers and buttons) or complex plenty to be themselves equanimous of other components.

Common CSS Pitfalls

To better sympathise the best practices provided beneath, it can exist helpful to review some common approaches that impede our goals of predictability, maintainability, reusability and scalability.

Pitfall: Modifying components based on context

          /* Modifying a component when it's in a sidebar. */ .sidebar .component {}                  

This may seem natural, only actually makes CSS less predictable and maintainable. Sooner or later you're going to demand that component mode somewhere other than a sidebar! Or, the reverse may happen: a new programmer places a component in the sidebar and gets an unexpectedly dissimilar appearance.

Pitfall: Relying on HTML construction

Mirroring a markup structure in our CSS selectors makes the resulting styles easy to pause (with markup changes) and hard to reuse (because it'due south tied to very specific HTML). This pitfall comes in several forms:

  • Overly complex selectors: nav > ul > li > a, commodity p:first-child
  • Qualified selectors: a.button, ul.nav

Pitfall: Overly generic class names

Similar to the pitfall of styling a component based on context, it's mutual to 'telescopic' a component'due south parts nether the parent component using a descendant selector:

          .widget {} .widget .title {} .widget .content {}                  

This CSS might seem economic, but tends to be counterproductive: .title and .content are too generic. A stand-lonely .title component created after will bear upon widget titles, likely without intending to.

Pitfall: Making a rule do too much

Applying positioning, margins, padding, colors, borders and text styles all in a single dominion overloads the rule, making it difficult or impossible to reuse if some parts (say, background, borders and padding) need to be practical to a similar component afterwards.

Pitfall: Needing to disengage styles

Creating manner rules that disengage other rules, like .component-no-padding makes CSS over-complex, hard to understand and maintain, and bloats the stylesheet. Needing such styles commonly indicates that some existing rules are doing too much.

Best Practices

1. Avert reliance on HTML structure

  • CSS should define the advent of an chemical element anywhere and everywhere it appears.

  • Apply classes to assign appearance to markup. Never utilize id selectors in CSS.

  • Go along selectors short. The best selector is a single class or element!

  • Sometimes multi-role selectors are pragmatic. For instance:

                  /**   * Add a horizontal rule betwixt next list rows   *   * Could be part of an implementation of the Pears "slats" component:   * http://pea.rs/content/slats-html5    */ .slat + .slat {   border-peak: 1px solid #cccccc; }                          

    Still, extra care should exist taken when using multi-part selectors:

    1. Avoid elements with no native semantics (div, span) in multi-role selectors.
    2. Avoid the descendent selector (east.g. .my-list li) where possible, peculiarly for components that may wrap other components. The descendant selector has a addiction of unintentionally affecting nested elements. Prefer the child selector: .my-list > li.
    3. Avert more than 2 combinators in a selector. The following rule is maxed out: .my-list > li > a.
    4. If in doubt, add a class and style the element directly.

ii. Define component elements (sub-objects) using their ain classes

To avoid relying on markup structure and overly-generic grade names, define a component's chemical element explicitly, prefixing them with the component's name followed by two underscores:

          
          .component {}  /* Component elements */ .component__header {} .component__body {}                  

Annotation that there is no demand to reverberate DOM structure in the class name; for instance, do not replace .menu li a with .menu__item__link. The class .menu__link should be sufficiently specific.

iii. Extend components using modifier classes

Create component variants explicitly, calculation a suffix with the variant proper noun preceded by two dashes. In guild to go on the stylesheet Dry, this modifier grade should only contain the styles needed to extend the original. This means that both base of operations and modifier classes must appear together in the markup:

CSS

          /* Push component */ .push {   /* styles */ }  /* Button modifier class */ .button--primary {   /* modifications and additions */ }                  

HTML

          <!-- Push variant is created by applying both component and modifier classes --> <button class="button button--primary">Salve</button>                  

4. Separate Concerns

Components should not be responsible for their positioning or layout within the site. Never apply widths or heights except to elements that natively accept these properties (e.k. images have these properties, so it'south okay to employ CSS to modify their width and meridian). Within components, separate structural rules from stylistic rules.

Dissever style from behavior by using dedicated classes for JavaScript manipulation rather than relying on classes already in apply for CSS. This way, we can alter classes for manner purposes without fear of breaking JS, and vice versa. To make the distinction articulate, classes used for JavaScript manipulation should be prefixed with 'js-'. These JavaScript hooks must never be used for styling purposes. See the department 'Formatting Form Names' for more information on naming conventions.

Avoid applying inline styles using JavaScript. If the behaviour is describing a state modify, apply a class proper name describing the state (e.g. 'is-active'), and let CSS to provide the appearance. Only use inline styles applied via JavaScript when the value of the style attributes must be computed at runtime.

Drupal viii/9 uses the SMACSS system to conceptually categorize CSS rules. Note that some SMACSS nomenclature has been changed to avoid confusion with existing Drupal terminology.

  1. Base of operations

    Base rules consist of styling for HTML elements but, such as used in a CSS reset or Normalize.css. Base rules should never include grade selectors.

    To avoid 'undoing' styles in components, base styles should reflect the simplest possible appearance of each element. For example, the simplest usage of the ul element may be completely unstyled, removing listing markers and indents and relying on a component class for other applications.

  2. Layout

    Arrangement of elements on the page, including filigree systems.

    Filigree systems should exist thought of equally shelves. They comprise content merely are not content in themselves. You put up your shelves then fill up them with your stuff [i.due east. components]. – Harry Roberts, CSS Guidelines

  3. Component (SMACSS "module")

    Reusable, discrete UI elements; components should course the bulk of Drupal'south CSS.

  4. State

    Styles that deal with transient changes to a component's appearance. Often, these are client-side changes that occur as the user interacts with the page, such as hovering links or opening a modal dialog. In some cases, states are static for the life of the page and are set from the server, such as the active element in master navigation. The main ways to style land are:

    • Custom classes, often but not ever applied via JavaScript. These should be prefixed with .is-, due east.g. .is-transitioning, .is-open;
    • pseudo-classes, such as :hover and :checked;
    • HTML attributes with state semantics, such as details[open];
    • media queries: styles that alter appearance based on the immediate browser environment.
  5. Theme

    Purely visual styling, such as border, box-shadow, colors and backgrounds, font backdrop, etc. Ideally, these should be separated plenty from a component's structure to be "swappable", and omitting these entirely should non break the component's functionality or basic usability.

v. Name Components Using Design Semantics

While the HTML5 specification mentions that course names should "describe the nature of the content," there'due south no reason for this. HTML elements already impart semantics on the content and machines cannot derive content-level semantics from class names (with the narrow exception of microformats.)

Class names should communicate useful data to developers. – Nicolas Gallagher, Nearly HTML Semantics and Front-End Architecture

Class names used equally CSS hooks should reverberate design semantics over content semantics. In general, they should reflect the intent and purpose of the design element they correspond.

Notation that this does not preclude presentational class names. Grid system classes such as .grid-3, utility classes such as .leader and .trailer (for adding whitespace based on a baseline grid) and .text-center are all examples of presentational classes that represent visual semantics. They are meaningful to developers, and highly reusable.

This does non hateful going back to classes like .bluish-box. This is obviously a bad class proper name since it does not reflect the visual meaning, only ane very surface attribute. It'due south useful to inquire "why is this a box, and why bluish?". Thinking well-nigh this, we might realize that this box is actually a version of the manner used throughout our site for notifications, and this item shade of blue is used for non-urgent notifications:

          
          .notification { /* full general styles for all notifications */ } .notification--info { /* bluish color adjustments */ }                  

Note for cadre developers

Since classes should represent design semantics and Drupal core must be blueprint-doubter, cadre default markup should be exceedingly cautious about what classes are included. This applies specially to the employ of presentational class names.

Notation for module developers

Since modules are responsible for providing the default HTML implementation, module developers should make their best endeavor to find an existing theme hook to apply and to insert a blueprint-derived course name, possibly one had already institute in cadre. If the module's content has no default design, the class name should be based on how the content is congenital; often this tin simply exist the name of the module (e.g. grade="views".)

Module developers should ensure that themers can replace/augment whatsoever module-provided class.

6. Formatting Class Names

Class names should use total words rather than abbreviations. Styles for a push button component should use due east.g. class="button" rather than class="btn"

Course names for components should always use a dash between words. Use class="button-group" rather than class="buttongroup"

The HTML grade aspect has been made to exercise a lot. Drupal uses a naming convention to make clear what a item class is for and what other parts of the system it affects:

          /* Component Rules */ .component-name .component-proper name--variant .component-name__sub-object .component-name__sub-object--variant  /* this configuration should be uncommon */  /* Layout Rules */ .layout-layout-method  /* eastward.g. '.layout-container' */ .grid-*  /**  * Country Classes  *  * These are e'er practical via JavaScript, and describe a non-default state.  */ .is-state  /* due east.g. '.is-active' */  /**  * Functional JavaScript Hooks  *  * When querying or manipulating the DOM from JavaScript, adopt dedicated   * classes non used for styling (or the id attribute).   * If using classes, prefix them with 'js-' to mark them for JS use.   * These 'js-' classes should not appear in stylesheets.  */ .js-behaviour-claw  /* e.1000. .js-slider, .js-dropdown */                  

Closing Notation: Specificity, ids and !of import

Avoid using the id selector in CSS. In that location is no general benefit to using the 'id' attribute as a CSS hook, and it has serious downsides in the form of increased selector specificity.

Although it should be avoided in CSS, there are many splendid uses for the 'id' attribute:

  • A performant JavaScript hook;
  • An ballast within the document for links (http://yoururl.com#anchor);
  • An anchor for associating labels with form elements or for associating DOM elements using ARIA attributes.

The !important flag should be used sparingly and appropriately, and in general should be restricted to themes. Since it overrides all external stylesheet rules, information technology is useful for states that must supersede all others, no matter the component variant. For example, error or disabled states are appropriate places to employ !important, since they must exist consistent and always use when nowadays. Never utilise !important to resolve specificity bug for general CSS rules. Additionally, Drupal core and contrib modules should avert the !of import flag, since all module CSS should be easy to override.

Case Study

Every bit an example and guide to developers, take the progress bar from the proposed Seven way guide:

Progress bar component and small variant

This might be marked up and styled every bit follows, using the standards described above:

HTML

          <div grade="progress">   <!--      .characterization is a split component, used for grade labels, simply tin can be applied     to non-label tags, and tin can be extended with a modifier class.     -->   <label form="characterization">Installing Node Module</label>      <!-- progress element (sub-object) -->   <div course="progress__track">     <!--        Component sub-objects don't need more than than the component proper name       every bit a prefix; progress__track__bar is verbose and unnecessary.               Inline styles shown here would exist practical past JavaScript using        the contained 'js-' form.       -->     <div course="progress__bar js-progress-percent" manner="width: 63%"></div>   </div>   <div grade="progress__description">     <!--       .layout-pull and .layout-push button are LTR/RTL-doubter utility classes for floating;        these should not announced in core default markup since they are not       design-contained.       -->     <div form="layout-pull">Installed 15 of 24 modules</div>     <strong course="layout-push">63%</strong>   </div>      <!--      Note that appearance is not tied to the tag; the appearance of the      <button> element would exist reset in the base of operations layer and styled equally      needed by applying classes.            Since this element uses an icon, it could be refactored to use a generic      icon container component.      -->   <button form="progress__cancel" href="#" title="cancel">abolish</push> </div>   <!--    Modifier classes create component variants; modifier classes must    exist used with the original grade in the markup   --> <div class="progress progress--small-scale">   <label class="label label--minor">Uploading syndey-opera-house-sunset.jpg</characterization>   <div class="progress__track">     <div class="progress__bar js-progress-percentage" style="width: 29%"></div>   </div>   <div class="progress__description">     <div form="layout-pull">Uploaded 221 of 762KB</div>     <strong class="layout-button">29%</strong>   </div>   <a class="progress__cancel" href="#" title="cancel"><bridge class="visually-subconscious">cancel</span></a> </div>                  

CSS (styles omitted)

          /**  * Progress Bar component  */ .progress {} .progress__track {} .progress__bar {} .progress__description {} .progress__cancel {} .progress__cancel:focus, .progress__cancel:hover {}   /**  * Progress Bar small-scale variant  */ .progress--small .progress__track {} .progress--small .progress__bar {} .progress--modest .progress__cancel {}                  

Annotation that the CSS relies almost exclusively on single class selectors; the exception is the pocket-sized variant. This uses descendant selector, simply is the recommended arroyo for styling sub-objects within variant components. Hither's why: firstly, it avoids extreme class names such equally .progress--small__bar which brainstorm to impairment the understandability of the code. 2nd, since we take avoided overly-generic grade names and since both parts of the selector are highly targeted classes, at that place is piffling risk of accidentally styling a further kid element. 3rd, scoping in this case is unlikely to break reusability, since nosotros should not wait a Progress track outside of the Progress element.

Nosotros are all the same serving of our goals well, and we greatly simplify the required markup: we simply need to add the variant class to the component itself: <div class="progress progress--small"><!-- all internals remain the same --></div>.

Acknowledgments

Portions of this guide are based heavily on:

  • Philip Walton, CSS Architecture
  • Johnathan Snook, SMACSS
  • Nicolas Gallagher, Well-nigh HTML semantics and front-end architecture

Additional Influence and Resources:

  • Nicole Sullivan, OOCSS
  • Harry Roberts, Code Smells in CSS
  • Harry Roberts, CSS-Guidelines

boothforgest.blogspot.com

Source: https://www.drupal.org/docs/develop/standards/css/css-architecture-for-drupal-9

0 Response to "Drupal Allow a Custom Css Client Upload"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel