Le langage CSS/Navigateurs et débogage

Débogage modifier

Un mauvais CSS peut perturber l'affichage des pages liées.

Les principales erreurs sont :

  • Accolades fermantes manquantes.
  • Point virgule manquant.
  • Identifications ou nommage des balises mal effectué.

Un bon moyen de vérifier si c'est le code HTML ou CSS qui est fautif, est de désactiver le CSS. Par exemple dans Firefox, menu "Affichage", choisir "style de page" à "aucun style". Le CSS ne sera alors plus pris en compte.

De plus, tous les navigateurs n'interprètent pas les classes de la même façon selon le code qui les appelle. En effet, le rendu CSS peut être très différent d'un navigateur à l'autre, c'est pourquoi après chaque modification, il faut tester au moins les quatre principaux engins (Gecko, Webkit, Trident, et Presto). Cela évitera un effort important de recherche de bug par la suite. Pour ce faire il existe des outils comme http://browsershots.org.

De plus, on peut utiliser JavaScript pour charger un code CSS plutôt qu'un autre selon le navigateur qu'il a détecté :

    <script type="text/javascript">
        alert(navigator.appCodeName);
    </script>

Checklist modifier

  1. Concernant le choix de passer par une classe ou un id, veuillez n'utiliser les classes que pour une collection d'éléments apparaissant dans plusieurs sections d'une même page. Sinon la collection peut être désignée par l'id de son conteneur.
  2. En cas d'espace entre des éléments qui n'en ont pas, assurez-vous que cela ne proviennent pas des marges ou des paddings.
  3. En cas de mise en page mystérieusement cassée, assurez-vous qu'il n'y a pas de retour à la ligne entre une balise anchor et une image ou span incrustée.
  4. Vérifier que les quatre coins de chaque élément sont visibles, par exemple avec un outil de modèle boite basé sur le navigateur (ex : Web Developer Toolbar pour Chrome, Firebug pour Firefox, Opera Dragonfly, ou IE Developer Toolbar) pour identifier les chevauchements. Si le coin droit est masqué à cause d'une trop grande largeur fixe de l'élément, réduire celle-ci. Si c'est la hauteur qui cache le coin du bas, on peut réduire la hauteur ou bien désactiver le chevauchement, ou encore repositionner les voisins qui avaient été placés en absolu, en relatif, ou avec des marges négatives.
  5. Utiliser les menus contextuels des styles appliqués dans votre Web development tools, pour voir quelles règles en cascade écrasent les voulues.
  6. S'assurer que l'élément parent utilisé pour augmenter la spécificité est disponible dans tous les templates.
  7. Dans le cas où l'URL ne passerait pas dans le validateur HTML[1], copier-coller le code HTML.
  8. Vérifier que le padding de chaque enfant ne force pas conteneur à s'étendre hors de ses dimensions, et réduire les dimensions en fonction, s'il es impossible d'éviter de définir à la fois le padding et la hauteur ou largeur dans le même élément.
  9. Vérifier lors du test de mise en page avec les barres d'outils du navigateur, qu'aucun bug min-height n'est déclenché en ajoutant ou retirant des menus du navigateur.
  10. Vérifier que les derniers styles définis ne sont pas écrasés par les existants avec plus de spécificité, ou par ceux définis ensuite en augmentant le poids du sélecteur en utilisant les références aux ID et classes parents.
  11. Utiliser l'inspecteur (CTRL + Shift + C) pour vérifier les écrasements des règles CSS localisées (les lignes rayées), pour voir s'il convient d'augmenter le poids d'un des sélecteurs.
  12. Vérifier la largeur et la hauteur des dimensions du conteneur autorisent suffisamment d'espace pour fournir le positionnement vertical et horizontal déclaré en CSS.
  13. Vérifier que la largeur et la hauteur de tous les éléments flottant tient dans le conteneur.
  14. Vérifier que la largeur du contenu aligné à droite, comme les labels, est juste large comme il faut, pour éviter d'utiliser des marges à gauche ou du padding pour l'alignement, car cela pourra être inconsistant selon les navigateurs.
  15. Vérifier que les éléments flottant avec du contenu enveloppant ont une largeur définie, avec un alignement de texte correct.
  16. Vérifier que les conteneurs étendant :hover ont une longueur et largeur par défaut plus grande ou égale à la taille des éléments imbriqués.
  17. Vérifier que les conteneurs de largeur fixe utilisent overflow:hidden pour que les blocs imbriqués rétrécis ne cause pas d'effondrement des marges dans les anciennes versions de Firefox.
  18. Vérifier que les éléments inline sont positionnés en absolue, ou contenus dans des éléments de bloc[2].
  19. Changer la position des attributs du conteneur pour s'assurer qu'il autorise le placement relatif ou absolu des éléments imbriqués.
  20. Pour déboguer les problèmes de positionnement, créer une copie du template et supprimer toutes les divs sauf les mal alignées et leurs adjacentes.
  21. Ajouter un conteneur div autour des éléments de niveau bloc qui ne répondent pas aux déclarations display:inline ou display:inline-block.
  22. Retirer les marges des divs internes en déboguant les valeurs de positionnement ignorées dans des divs en positions absolues.
  23. Pour déboguer les problèmes de hauteur et largeur, retirer tous les textes inline et commencer par un espace insécable comme contenu de placeholder.
  24. Pour déboguer les problèmes d'héritage invisibles, définir les marges, paddings, tailles de police et bordures à zéro.
  25. Utiliser display:block avec une hauteur fixe si les marges sont incohérentes pour le texte inline, dans les situations telles que la création d'un en-tête utilisant une balise, ou d'un élément d'un seul pixel de haut avec décalages de marges créant des coins ronds.
  26. Utiliser un unique background-position pour chaque ligne pour créer des coins arrondis avec une image en arrière-plan recouvrant la moitié du conteneur mais pas l'autre.
Demande de traduction 

Cette page nécessite une traduction.
Cette page est en anglais. Si vous connaissez cette langue et le sujet de la page, vous pouvez poursuivre ou corriger la traduction.


Use obvious background colors to highlight misplaced or misaligned nested elements when debugging inner divs

Use inline styles and remove ID and class references to display elements that are invisible due to an unknown CSS error

Use word-wrap:break-word(CSS3 Property) or wbr(and its alternatives) to break lines within long words to prevent overflow of an unbreakable string from causing horizontal scrollbars or inadvertent wrapping of blocks to a new line

Use divs instead of paragraphs when margins don't take effect

Use divs instead of paragraphs to avoid the inherit vertical margins between paragraphs

Use display:inline on an absolutely positioned elements to avoid hasLayout issues

Use margins to move absolutely positioned elements instead of directional shifts

Use border-collapse: collapse; and border-spacing:0 to remove gaps between table columns

Use border styling on the td element instead of the tr element after doing the above to create grid lines on a table

Use empty-cells: hide to remove borders from empty table cells

Use position:relative on inline text and position:absolute on block-level containers and media

Use inline-block to give hasLayout to a relatively positioned container

Make sure class selectors aren't inadvertently overridden by default values of ID selectors, especially background-position changes for sprites, by dividing the properties of ID selectors using longhand notation

Use overflow:visible on parent elements if negative margins don't reveal overflow content

Create more classes with specific names instead of creating more complex parent=>child references

Make sure there's not a more specific CSS rule or one that comes later in the style sheet which is overriding the desired effect

Make sure the there's not a number at the beginning of the ignored class or ID name

If the property value for a group of elements doesn't work, redefine that property value for one of those elements to see if a comma is missing or an unsupported selector nullified the entire rule

If neighboring elements are mysteriously repositioned when an event or hover triggers the display or a submenu or other hidden content, make sure that content is not relatively positioned in external CSS, inline CSS, or generated JavaScript attributes.

If margins between a series of lists with headers are inconsistent due to special cases such as scrollbars for overflow in long lists or different margins for the first or last list, remove margins from the lists themselves and put them on the headers and use padding at the top and bottom of the container to handle spacing between the first or last list and the borders

If a border does not show up on around an element, make the color black or white to see if the color is too light or dark to distinguish from the background

If a div is being pushed beneath its specified position to a new line, use the mouse to select the content within the div to see if the dimensions of a block element within it are causing overflow outside the container. Make sure to set the width of any forms within the container in addition to validating the HTML to make sure no block tags are missing or inline tags have block tags nested within them.

If a hover or visited state of a hyperlink is not working correctly, do the following checks: -Make sure the pseudo classes are defined in the correct order -Make sure the pseudo classes don't share the same definition as a less-specific element, like a:hover{color: #ccc;} and .mylink:hover{color: #ccc;} since the browser will group them together and parse the less-specific rules in the cascade before the more specific rule, such as .mysite{color: #eee;}. If this is the case, add a reference to the parent container to the pseudo class rules, for example .mymenu .mylink:hover{color: #ccc;} to increase the selector weight. -Make sure the pseduo classes are defined or the element selector instead of the class selector, for example .nav a:hover vs nav a.submenu:hover. This may not work in IE6. -Make sure the rules are defined in the proper order, which is the following: 1. :link, :visited 2. :hover, :focus 3. :active

Since a link can simultaneously be in the :visited, :hover, and :active states, and they have the same specificity, the last one listed wins.

Increase or decrease the text inside a container to make sure it wraps text and resizes properly

Increase or decrease the font size of the browser a few times to see how it affects your backgrounds and margins, especially for text used in headings and navigation

Apply classes to different elements to make sure each class is not dependent upon a specific tag

Include several block elements such as a few paragraphs and a large list inside a div to see if it breaks the flow of the container

Use clear to break an element away from a floated sibling and wrap it to a new line

Separate HTML structure and CSS design by developing the naming conventions and organization of the container styles without thinking about the content

Create a reusable library of headers, footers, submenus, navigation bars, lists, forms, and grid layouts

Use consistent semantic style names for classes and IDs

Design modules to be transparent on the inside

Extend objects by applying multiple classes to an element

Use CSS reset styles, web-safe fonts, and grids on all projects

Avoid location dependent styles that break outside of the cascade

Avoid using a class name that describes the tag or property it is mapped to, such as .hidediv or .floatleft

Avoid using IDs to style content within the main layout containers

Avoid using images to replace text

Avoid drop shadows and rounded corners over irregular backgrounds

Avoid nesting divs inside of spans or having spans adjacent to divs to prevent triggering side-effects caused by the behavior of anonymous block boxes

Any vertical-align value besides top or bottom will be rendered inconsistenly across browsers for form elements

Only use the !important declaration to create user style sheets or to override an inline style if the HTML markup is not editable. The !important declaration must follow the value of the property that it intends to give weight to. Since inline styles can be added to any HTML tag, using the style attribute selector is the only way to override those styles if a class or ID attribute is not defined for the element, as in the following example:

div[style]{ background-color: #f00 !important; }

Use an abs pos span nested inside an href to create dropdowns that show up in different places

Use the nested span trick to highlight the parent container of a nav list by setting it's background color to the desired nav background and making it visible on hover. Make the ul the rel pos parent and give it overflow hidden, and make the empty span bottom:0; z-index:-1; height: 99em; and width equal to the nav

 <ul id="nav"><li><a href="#"><span></span>Test 1</a></li></ul>

Use the nested span trick to create polygonal shaped links by offsetting their background positioning and placing them over the desired content

Use a:focus{width:0,height:0,outline:0} to remove dotted borders

Use resets to debug margin/padding issues

Use margins is remove padding and top/bottom positioning for abs positioned elements if spacing is off

Use :default to select all radio button sets

Make sure parent div used for specificity is available in all templates

Use relative/absolute div with a background color to replace text with ellipsis using the follwing steps:

Create a content div with the original content and a height equal to the font-size * the number of rows you want visible

When a JavaScript event is triggered, reduce the height to the new number of rows you want visible by adding a class with that setting

Make sure class selectors aren't inadvertently overridden by default values of ID selectors, especially background-position changes for sprites, by dividing the properties of ID selectors into pieces

Use change events to delegate input and select elements

Use active link states and relative positioning to respond to link clicks

Use the following alternatives for buffering offscreen content: -Negative margins instead of display:none -Relative positioning offsets instead of visibility:hidden for text -background-position instead of visibility:hidden for images -display:inline block instead of display:table -clip:rect instead of max-width/height

Absolutely positioned elements moved outside of their relatively positioned parents in Firefox 2 cause the containers to stretch

Use margins for the outermost elements

Use padding for elements that have a background color or image

-moz-only-whitespace matches an element that has no child nodes at all or empty text nodes or text nodes that have only white-space in them. Only when there are element nodes or text nodes with one or more characters inside the element, the element doesn't match this pseudo-class anymore.
-moz-selection (::selection) pseudo-element applies to the portion of a document that has been highlighted (e.g. selected with the mouse) by the user.

The :-moz-first-node pseudo-class matches an element that is the first child node of some other element. It differs from :first-child because it does not match a first child element with (non-whitespace) text before it.

The :-moz-last-node pseudo-class matches an element that is the last child node of some other element. It differs from :last-child because it does not match a last child element with (non-whitespace) text after it.

The ::-moz-list-bullet pseudo-class is used to edit the bullet of a list element.

The :default pseudo-class is used to identify a user interface element that is the default among a group of similar elements

Use -ms-text-align-last for orphan lines at the end of paragraphs

Use outlines to style buttons with white accents

Use q { quotes: '"' '"' } to define quote characters

Use the following to trigger quote character display:

q:before { content: open-quote }
q:after  { content: close-quote }

Use fixed positioning with @media print to show header and footer containers on every page

Use absolute:positioning instead of fixed positioning to avoid showing header and footer containers on every page

Bootstrap modifier

Remplacer :

  • mb + mt = my
  • ml + mr = mx

Préfixes automatiques modifier

Certains outils permettent d'automatiser l'ajout des préfixes dépendant des navigateurs[3], comme gulp.js[4].

Voir aussi modifier

Références modifier