Outils pour utilisateurs

Outils du site


issue134:c_c

Ceci est une ancienne révision du document !


This past month has been spent streamlining my development process, in order to more quickly create prototypes and advance onward to finalized styles. Part of this included watching a video from Adam Wathan (one of the creators of Tailwind CSS). In this video on YouTube, he used Tailwind to quickly create the new https://refactoringui.com/ design. It inspired me to give it a shot, and this article will offer some examples, and my insights.

Le mois dernier a été passé à la rationalisation de mon processus de développement de façon à créer des prototypes plus rapidement et de progresser vers des styles finalisés. Parmi tout ça, il y eu le visionnage d'une vidéo d'Adam Wathan (un des créateurs de Tailwind CSS). Dans cette vidéo de Youtube, il utilisait Tailwind pour créer rapidement le nouveau concept https://refactoringui.com/. Il m'a inspiré d'y jeter un œil, et cet article offrira quelques exemples, et mes réflexions.

What is Tailwind CSS? Tailwind CSS is a framework that offers utility classes (similar to some functional CSS frameworks). The utility classes essentially store typical CSS settings in a class - such as the class “shadow” instead of defining a shadow by hand. However, it also offers a function “@apply” to apply a combination of classes within CSS, which can cut down on the repetition that appears in HTML. This is a feature I did not know about, until using it. You can also customize Tailwind massively by using their tailwind.js file.

Qu'est-ce que Tailwind CSS ?

Trailwind CSS est un framework qui offre des classes d'utilitaires (similaires à certains frameworks fonctionnels de CSS). En gros, les classes d'utilitaires stockent desparamètres CSS typiques dans une classe _ _telle que la classe « shadow » (ombre) au lieu de définir une ombre à la main. Cependant, il offre aussi une fonction « @apply » pour appliquer une combinaison de classes dans CSS, qui peut réduire la répatition qui apparaît dans HTML. C'est une fonctionnalité dnont je n'avais pas entendu parler, jusqu'à ce que je l'utilise. Vous pouvez aussi personnaliser très largement Tailwind en utilisant le fichier tailwind.is.

Why? Prototyping typically requires a bit of back and forth on different CSS settings, and the defaults shipped with Tailwind (and the ability to customize it) are perfectly sane. So instead of jumping between an HTML file and a CSS file (and possibly waiting for your preprocessor to compile), you can instead stick to the HTML view and simply attach classes as you need to the various elements. I find this approach is much faster than jumping between HTML and CSS, and also gives you a starting point for appearance (as opposed to creating your own default shadows, borders, backgrounds, etc.). Then, once you’ve prototyped the system, you can reduce repetition of classes by creating your own custom class names and styles, and using the exact settings from the prototype thanks to @apply. For examples please see the codepen and following sections.

Pourquoi ?

Le prototypage réclame classiquement des allers er retours sur les différents réglages de CSS, et les valeurs par défaut livrées avec Tailwind (et la possibilité de les personnaliser) sont bien vues. Aussi, au lieu de faire la navette entre un fichier HTML et le fichier CSS (et probablement d'attendre que votre préprocesseur compile), vous pouvez à la place rester sur votre vue HTML et simplement attacher des classes aux différents éléments quand vous en avez besoin. Je trouve cette approche plus rapide que la navette HTML-CSS et elle vous donne un point de départ pour l'apparence (à l'inverse de la création de vos propres ombres, bordures, fonds, etc.).

Ensuite, une fois que vous avez prototyper le système, vous pouvez réduire la répétition des classes en créant vous propres classes et styles personnalisés, et en utilisant les paramètres exacts du prototype, grâce à @apply. Pour les exemples, voyez le codepen et les sections suivantes.

Preamble In order to follow along with this article (and to have easy access to all the files I used), I created the following two codepens: • https://codepen.io/lswest/full/ XYKVVw/ - This is Part 1, where we use only the utility classes Tailwind offers. • https://codepen.io/lswest/full/ LrZeaZ/ - This is Part 2, where we extract repeated combinations of classes, and turn them into our custom styles. Note: To view the HTML in the above examples, you’ll need to change the view to “editor view”, or view the source of the page. You’ll also need to have nodejs and npm installed. I would also recommend (not required) using something like Atom or Visual Studio Code set up with Emmet (automatically available in Code).

Préambule

De façon à suivre cet article ( et pour avoir un accès ffacile à tous les fichiers que j'ai créé), j'ai créé les deux codepen suivants : • https://codepen.io/lswest/full/XYKVVw/ - C'est la partie 1, où nous n'utilisons que les classes d'utilitaires offertes par Tailwind. • https://codepen.io/lswest/full/LrZeaZ/ - C'est la partie 2, où nous extrayons les combinaisons de classes répétitives et les transformons en styles personnalisés.

Note : pour voir le HTML dans les exemples ci-dessus, vous devez changer la vue en « editor view » (vue de modification) ou voir la source de la page.

Vous aurez aussi besoin que nodejs et npm soient installés.

Je vous recommanderais aussi (sans obligation) d'utiliser quelque chose comme Atom ou Visual Studio paramétré avec Emmet (disponible automatiquement dans Code).

Getting Set Up • Create a folder you want to work on this project. • Visit one of the codepens listed above, and copy the contents of the package.json file into your own package.json file • Run npm install to install all the relevant packages. • Run ./node_modules/.bin/tailwind init in order to generate your own tailwind.js file. • Visit the first codepen above, and copy all the files into the relevant locations (listed in the pen). • Once the files are in the correct locations, you’ll want to run either npm run or npm run watch. This will run webpack and generate the ./dist/styles.css file.

Paramétrage

• Créez un dossier dans lequel vous voudrez travailler à ce projet. • Allez sur un des codepen cités au-dessus et copiez le contenu du fichier package.json dans votre propre fichier package.json. • Lancez npm install pour installer tous les paquets nécessaires. • Lancez ./node_modules/.bin/tailwind init de façon à générer votre propre fichier tailwind.js. • Allez sur le premier codepen cité au-dessus et copiez tous les fichiers dans les emplacements correspondants (listés dans le pen). • Une fois que tous les fichiers osnt à la bonne place, vous lancerez, soit npmrun, soit npm run watch. Ceci lancera webpack et générera le fichier ./dist/styles.css.

Note: If you’re installing these packages by hand into a custom package.json file, at the time of writing you will need to install extract-text-webpack-plugin@next (the beta version) for it to be compatible with Webpack 4. Note #2: While Tailwind is available via CDN, using it removes some of the flexibility, as you have no control over the tailwind.js file. If you just want to try it out, feel free to use the CDN. If, however, you’re looking to customize it, definitely use some form of precompiler as explained in the documentation.

Note : Si vous installez ces paquets à la main dans un fichier personnalisé package.json, à l'heure où j'écris, vous devrez installer extract-text-webpack-plugin@next (la version beta) pour qu'il soit compatible avec Webpack 4.

Note n°2 : Alors que Tailwind est disponible via CDN, l'utiliser enlève un peu de flexibilité, car vous n'avez plus de contrôle du fichier tailwind.js. Si vous voulez juste le tester, n'hésitez pas à utiliser CDN. Cependant, si vous souhaitez le personnaliser, utilisez, sans aucun doute, une des sortes de précompileur comme expliqué dans la documentation.

Explaining the HTML In both codepens, the HTML is pretty similar. I used pre tags (for preformatted) to ensure the formatting of the files worked alright, and simply included a small header to indicate what project this is. The majority of the boilerplate was generated using the emmet html:5 abbreviation, and then the viewport was added (meta:vp). I originally threw all the content into the file using blank HTML elements. This means the header originally looked like this: <header> <h1>Command &amp; Conquer: Tailwind CSS</h1> </header> None of the HTML is too crazy, and so I will leave the explanation here. What follows now is the prototyping phase, where we utilized the Tailwind CSS utility classes.

Explication du HTML

Dans les deux codepens, le HTML est assez proche. J'ai utilisé des balises pre (pour preformaté) pour m'assurer que le formatage des fichiers fonctionne bien et inclus simplement une petite en-tête pour indiquer de quel projet il s'agit. La majorité du texte standard a été généré en utilisant l'abréviation emmet html:5 et ensuite la vue d'écran a été ajoutée (meta:vp).

À l'origine, j'avais tiré tout le contenu dans le fichier en utilisant des éléments HTML vierges. Ceci veut dire qu'au début, l'en-tête ressemblait à ça :

<header>

<h1>Command &amp; Conquer: Tailwind CSS</h1>

</header>

I ln'y a rien de trop difficile dans le HTML, et, donc, je vais m'arrêter ici pour les explications. Ce qui suit maintenant, est la phase de prototypage, où nous avons utilisé les classes d'utilitaires de Tailwind CSS.

Adding Utility Classes Anyone who has copied the HTML from my first codepen link, will notice that there are a lot of styles added. I’ll run through some of the classes, but they are generally self-explanatory. <body class=“font-sans leading-tight antialiased h-screen”> <header class=“bg-orange”> <h1 class=“text-center text-grey-lighter py-8”>Command &amp; Conquer: Tailwind CSS</h1> </header> <main class=“container mx-auto mt-16”> This is the first 5 lines of the pen. The first class on the body tag are telling the browser to use the font-sans class, which is where Tailwind defines a sans font family. The other classes are simply informing the browser to antialias the fonts, and apply tight leading (a typography term referring to the vertical spacing between lines of text).

Ajout des classes d'utilitaires

Toute personne qui a copié le HTML à partir de mon premier lien vers codepen notera que beaucoup de styles ont été ajoutés. Je passerai sur certaines de ces classes, mais elles sont en général faciles à comprendre.

<body class=“font-sans leading-tight antialiased h-screen”>

  <header class="bg-orange">
      <h1 class="text-center text-grey-lighter py-8">Command &amp; Conquer: Tailwind CSS</h1>
  </header>
  <main class="container mx-auto mt-16">
  

C'est les cinq premières lignes du pen. La première classe de la balise de « body » dit que le navigateur utilise la classe font-sans, là où Tailwind définit une famille de polices « sans ». les autres classes sont informent simplement le navigateur d'applique l'anti-alias sur les polices ainsi qu'un qu'un interlignage serré (un terme de typographie faisant référence à l'espacement vertical des lignes du texte).

The header gets the default orange as a background, and the h1 is centered, made a light grey color, and receives padding on the y-axis (top and bottom) of “8”. This “8” is defined in the tailwind.js file, and by default is 2rem (for a total of 4 rem, split between the top and the bottom). These numbers (by default) are the rem value * 4. The main element is a container (where the width is limited based on screen size), and the mx-auto class adds auto margins on the left/right (x-axis). This essentially centers the container in the middle of the screen. The mt-16 adds padding to the top. By default tailwind.js only defines up to mt-8. In order to add mt-16 like I’m using, you’ll need to add the following line: '16': '4rem', This line should go at the end of the margin array (simply search the file for “margin:”). Once webpack has recompiled the styles, you’ll have access to mt-16.

Le fond de l'en-tête est orange, la couleur par défaut, et la partie « h1 » est centrée, avec une couleur grise légère, et reçoit une guirlande de « 8 » sur l'axe y (en haut et en bas). Ce « 8 » est définit dans le fichier tailwind.js et, par défaut, est 2rem (pour un total de 4 rem, répartis entre le haut et le bas). Ces chiffres (par défaut) sont la valeur de rem * 4.

L'élément principal est un conteneur (où la hauteur est limité sur la base de la taille de l'écran); et la classe mx-auto ajoute des marges automatiques à droite et à gauche (axe x). Ceci centre en gros le conteneur au milieu de l'écran. Le paramètre mx-auto ajoute un feston au sommet. Par défaut, tailwind.js ne définit que jusqu'à mt-8. Pour ajouter mt-16 comme je l'ai utilisé, vous aurez besoin d'ajouter la ligne suivante :

'16': '4rem',

Cette ligne devra aller à la fin de la zone des marges (cherchez juste « margin: » dans le fichier). une fois que webpack a recompilé les styles, vous aurez accès à mt-16.

Customizing Tailwind As you saw at the end of the last section, changing settings and defaults for Tailwind is extremely simple. For prototyping something, you may not want to remove any defaults, and instead simply add to it (as we did with the margins above). Once you’re ready to go into production (or if you’re following a style guide), then I would highly recommend removing all unnecessary colors, and adding/editing them to match the given styles. This will reduce the resulting CSS file immensely (as each color is used for backgrounds, text and borders). Naturally, as you continue your project, you may need to adjust screen sizes, margins, shadows, etc. - which you are free to do at any time. I simply recommend starting with the colors, as these are fundamental, and can have a large impact on the number of classes.

Personnalisation de Tailwind

Comme vous l'avez vu à la fin de dernière section, les changements de paramètres et de valeurs par défaut sont extrêmement simples. Pour prototyper quelque chose, vous pourriez vouloir enlever toutes les valeurs par défaut et simplement, à la place, y faire des ajouts (come vous l'avez fait ci-dessus avec les marges). Une fois que vous êtes prêts à passer en production, (ou si vous suivez un guide de style), je vous recommanderais vivement ensuite d'enlever toutes les couleurs inutiles et d'ajouter/corriger celles qui correspondent aux styles indiqués. Ceci réduira très fortement le fichier CSS résultant (car chaque couleur est utilisée pour les fonds, le texte et les bordures).

Naturellement, en continuant votre projet, vous pourriez avoir besoin d'ajuster les tailles d'écran, les marges, les ombres,etc. - ce que vous êtes libres de faire à n'importe quel moment. Je recommande juste de commencer par les couleurs car elles sont fondamentales et peuvent avoir un large impact sur le nombre de classes.

The Design The design of my codepen is pretty simple - I chose an orange color because that is prevalent in Full Circle Magazine, and otherwise just stuck to grey and black for legibility. I make ample use of the inline/block, overflow, rounded, and the bg/text classes. The rounded class simply rounds the corners of the pre tags, and the inline/block classes add display:inline or display:block to the elements. The overflow-x-auto is used on the pre tags to avoid text running outside of the grey background on smaller devices, and the webpack.config.js file gets overflow-y-auto and a height (64 = 16rem). This is due to the length of the file - I wanted to keep the HTML file from getting too long, and the webpack file will remain unchanged throughout this article. This prototype took me less than 10 minutes in total (to the state of codepen part 1). While it isn’t the most complex, it’s also visually attractive enough to leave it be at that point. I would have previously either had much less polished CSS, or simply not be finished at this point.

La conception

La conception de mon codepen est plutôt simple - j'ai choisi une couleur orange car elle est fréquente dans le Full Circle Magazine, et autrement, je m'en suis tenu au gris et au noir pour la lisibilité.

J'ai fait une large utilisation des classes inline/block, overflow, roundedet

The Repetition Instead of removing all the classes from Tailwind and doubling my efforts by giving every element specific styles or a specific class, I instead focused only on those elements I repeated. This is essentially 3 styles to define: • code blocks (block display, grey background, vertical padding of 2rem, rounded corners, and overflow-x: auto;) • pre - in the process steps, I repeat “inline” classes a lot. As such, I made the display: inline; the default one, and simply added class=”block” to the file tree, and integrated it into the code class. • h3 - These should be orange. While it is a single class that we are replacing, imagine if you decide you want to use a red color? You wouldn’t want to define “orange” as a red color, nor would you want to adjust a bunch of styles in various HTML locations. Instead, I use an element selector, and simply move the text-orange setting into CSS. This way any changes occur in one location.

Using @apply Using @apply is extremely simple. After the imports in the src/styles.css file, you simply define your class as normal, and then write @apply <classes from HTML>. Do keep in mind that you need to add a period in front of the class names if you copy them directly from the HTML, as you are writing CSS selectors. Example: .code { @apply .block .bg-grey .py-4 .rounded .overflow-x-auto } When webpack recompiles the file, this @apply will be replaced with the actual styles from the classes listed. For the other two styles, check the second codepen for the contents of my src/styles.css file.

Extra Features Tailwind also offers special classes to allow you to define styles by screen size, or to style a hover state. For example: <button class=”w-full md:w-1/3 hover:bg-orange”> Button </button> The classes in that example defines the button’s width to be 100% by default. On medium devices (breakpoint is defined in tailwind.js) the width is then ⅓, and on hover the background should become orange.

If you want to use these classes in @apply, you will need to remove the definition before the colon. So for the hover state: button:hover { @apply .bg-orange } Similarly with the md, you’d need to place that within a media query.

Next Steps Once you’ve created your website using Tailwind CSS, you may want to reduce the file size of your CSS. This can be done by removing unused settings from the tailwind.js file, and possibly adjusting the modules available. The documentation for Tailwind has details here: https://tailwindcss.com/docs/controlling-file-size

Conclusion I hope this article is of interest to some people. Hopefully it will also encourage a few people to try out Tailwind after having previously dismissed it (as I originally did). If this was interesting, but you’re more of a designer than a developer, feel free to look at Refactoring UI. If you enjoyed this format of article, please let me know by writing to me at lswest34+fcm@gmail.com. If you want to request an article, or see something that needs to be corrected, I can be reached at the above email for that as well.

Further Reading https://refactoringui.com/ - Project by Steve Schoger and Adam Wathan where they offer design tips. https://youtu.be/17OBlxY2C_0 - The video I refer to in the introduction. Adam Wathan does stream a lot of live coding, if that is of interest to you as well. https://tailwindcss.com/docs/what-is-tailwind - The Tailwind CSS documentation.

issue134/c_c.1531223830.txt.gz · Dernière modification : 2018/07/10 13:57 de d52fr