Package cssutils.css — cssutils 0.9.8 documentation

### Navigation

- index
- modules |
- next |
- previous |
- cssutils 0.9.8 documentation »

# Package `cssutils.css`

Classes implementing DOM Level 2 CSS and CSS Module: Namespaces (W3C Working Draft 28 August 2006)

## `CSSStyleSheet`

A CSSStyleSheet contains all rules. It consists of the different CSS rules like `CSSImportRule`, `CSSStyleRule` etc. It also defines the encoding of the style sheet used for serialization. The encoding might by set with an `CSSCharsetRule` rule or simpler with the `encoding` attribute. The serialized sheet may be obtained from `cssText`. All rules are present in `cssRules`, a stylesheet iterates on its rules so this might be easier. Namespaces are available via `namespaces` (do not rely on prefixes, see http://www.w3.org/TR/REC-xml-names/ how these work). Variables are available via `variables` which is a `CSSVariablesDeclaration` and contains all available variables including the ones defined in imported style sheets. Changes to this object do NOT change the parent sheet!

class `cssutils.css.` `CSSStyleSheet`(href=None, media=None, title=u'', disabled=None, ownerNode=None, parentStyleSheet=None, readonly=False, ownerRule=None, validating=True)

  CSSStyleSheet represents a CSS style sheet.

  Format:

      stylesheet
        : [ CHARSET_SYM S* STRING S* ';' ]?
          [S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
          [ namespace [S|CDO|CDC]* ]* # according to @namespace WD
          [ [ ruleset | media | page ] [S|CDO|CDC]* ]*

  `cssRules`
    All Rules in this style sheet, a `CSSRuleList`.
  `add`(rule)

    Add rule to style sheet at appropriate position. Same as `insertRule(rule, inOrder=True)`.

  `alternate`

    Not used in cssutils yet.

  `cssText`

    Textual representation of the stylesheet (a byte string).

  `deleteRule`(index)

    Delete rule at index from the style sheet.

    Parameters: | index – The index of the rule to be removed from the StyleSheet’s rule list. For an index < 0 no `IndexSizeErr` is raised but rules for normal Python lists are used. E.g. `deleteRule(-1)` removes the last rule in cssRules. index may also be a CSSRule object which will then be removed from the StyleSheet.
    Exceptions : | `IndexSizeErr`: Raised if the specified index does not correspond to a rule in the style sheet’s rule list. `NamespaceErr`: Raised if removing this rule would result in an invalid StyleSheet `NoModificationAllowedErr`: Raised if this style sheet is readonly.

  `encoding`

    Encoding set in `CSSCharsetRule` or if `None` resulting in default `utf-8` encoding being used.

  `href`

    If the style sheet is a linked style sheet, the value of this attribute is its location. For inline style sheets, the value of this attribute is None. See the href attribute definition for the LINK element in HTML 4.0, and the href pseudo-attribute for the XML style sheet processing instruction.

  `insertRule`(rule, index=None, inOrder=False, _clean=True)

    Used to insert a new rule into the style sheet. The new rule now becomes part of the cascade.

    Parameters: | rule – a parsable DOMString, in cssutils also a `CSSRule` or `CSSRuleList` index – of the rule before the new rule will be inserted. If the specified index is equal to the length of the StyleSheet’s rule collection, the rule will be added to the end of the style sheet. If index is not given or `None` rule will be appended to rule list. inOrder – if `True` the rule will be put to a proper location while ignoring index and without raising `HierarchyRequestErr`. The resulting index is returned nevertheless.
    Returns: | The index within the style sheet’s rule collection
    Exceptions : | `HierarchyRequestErr`: Raised if the rule cannot be inserted at the specified index e.g. if an @import rule is inserted after a standard rule set or other at-rule. `IndexSizeErr`: Raised if the specified index is not a valid insertion point. `NoModificationAllowedErr`: Raised if this style sheet is readonly. `SyntaxErr`: Raised if the specified rule has a syntax error and is unparsable.

  `namespaces`

    All Namespaces used in this CSSStyleSheet.

  `ownerNode`

    Not used in cssutils yet.

  `ownerRule`

    A ref to an @import rule if it is imported, else `None`.

  `parentStyleSheet`

    For style sheet languages that support the concept of style sheet inclusion, this attribute represents the including style sheet, if one exists. If the style sheet is a top-level style sheet, or the style sheet language does not support inclusion, the value of this attribute is None.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `setSerializer`(*args, **kwargs)

    Set the cssutils global Serializer used for all output.

  `setSerializerPref`(*args, **kwargs)

    Set a Preference of CSSSerializer used for output. See `cssutils.serialize.Preferences` for possible preferences to be set.

  `type`

    This specifies the style sheet language for this style sheet. The style sheet language is specified as a content type (e.g. `text/css`). The content type is often specified in the ownerNode. Also see the type attribute definition for the LINK element in HTML 4.0, and the type pseudo-attribute for the XML style sheet processing instruction. For CSS this is always `text/css`.

  `variables`

    A `cssutils.css.CSSVariablesDeclaration` containing all available variables in this CSSStyleSheet including the ones defined in imported sheets.

## CSS rules

### `CSSRule`

class `cssutils.css.` `CSSRule`(parentRule=None, parentStyleSheet=None, readonly=False)

  Abstract base interface for any type of CSS statement. This includes both rule sets and at-rules. An implementation is expected to preserve all rules specified in a CSS style sheet, even if the rule is not recognized by the parser. Unrecognized rules are represented using the `CSSUnknownRule` interface.

  `CHARSET_RULE` = 2

    `cssutils.css.CSSCharsetRule` (not used in CSSOM anymore)

  `COMMENT` = 1001

    `cssutils.css.CSSComment` - not in the offical spec, Value has changed in 0.9.7a3

  `FONT_FACE_RULE` = 5

    `cssutils.css.CSSFontFaceRule`

  `IMPORT_RULE` = 3

    `cssutils.css.CSSImportRule`

  `MEDIA_RULE` = 4

    `cssutils.css.CSSMediaRule`

  `NAMESPACE_RULE` = 10

    `cssutils.css.CSSNamespaceRule`, Value has changed in 0.9.7a3 due to a change in the CSSOM spec.

  `PAGE_RULE` = 6

    `cssutils.css.CSSPageRule`

  `STYLE_RULE` = 1

    `cssutils.css.CSSStyleRule`

  `UNKNOWN_RULE` = 0

    `cssutils.css.CSSUnknownRule` (not used in CSSOM anymore)

  `VARIABLES_RULE` = 1008

    `cssutils.css.CSSVariablesRule` - experimental rule not in the offical spec

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of the rule. This reflects the current state of the rule and not its initial value.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

  `wellformed`

    If the rule is wellformed.

### `CSSRuleList`

class `cssutils.css.` `CSSRuleList`(*ignored)

  The CSSRuleList object represents an (ordered) list of statements.

  The items in the CSSRuleList are accessible via an integral index, starting from 0.

  Subclasses a standard Python list so theoretically all standard list methods are available. Setting methods like `__init__`, `append`, `extend` or `__setslice__` are added later on instances of this class if so desired. E.g. CSSStyleSheet adds `append` which is not available in a simple instance of this class!

  `append`(*ignored)

    Implemented in class using a CSSRuleList only.

  `count`(value) → integer -- return number of occurrences of value
  `extend`(*ignored)

    Implemented in class using a CSSRuleList only.

  `index`(value[, start[, stop]]) → integer -- return first index of value.

    Raises ValueError if the value is not present.

  `insert`()

    L.insert(index, object) – insert object before index

  `item`(index)

    (DOM) Retrieve a CSS rule by ordinal index. The order in this collection represents the order of the rules in the CSS style sheet. If index is greater than or equal to the number of rules in the list, this returns None.

    Returns CSSRule, the style rule at the index position in the CSSRuleList, or None if that is not a valid index.

  `length`

    (DOM) The number of CSSRules in the list.

  `pop`([index]) → item -- remove and return item at index (default last).

    Raises IndexError if list is empty or index is out of range.

  `remove`()

    L.remove(value) – remove first occurrence of value. Raises ValueError if the value is not present.

  `reverse`()

    L.reverse() – reverse IN PLACE

  `rulesOfType`(type)

    Yield the rules which have the given type only, one of the constants defined in `cssutils.css.CSSRule`.

  `sort`()

    L.sort(cmp=None, key=None, reverse=False) – stable sort IN PLACE; cmp(x, y) -> -1, 0, 1

### `CSSCharsetRule`

class `cssutils.css.` `CSSCharsetRule`(encoding=None, parentRule=None, parentStyleSheet=None, readonly=False)

  The CSSCharsetRule interface represents an @charset rule in a CSS style sheet. The value of the encoding attribute does not affect the encoding of text data in the DOM objects; this encoding is always UTF-16 (also in Python?). After a stylesheet is loaded, the value of the encoding attribute is the value found in the @charset rule. If there was no @charset in the original document, then no CSSCharsetRule is created. The value of the encoding attribute may also be used as a hint for the encoding used on serialization of the style sheet.

  The value of the @charset rule (and therefore of the CSSCharsetRule) may not correspond to the encoding the document actually came in; character encoding information e.g. in an HTTP header, has priority (see CSS document representation) but this is not reflected in the CSSCharsetRule.

  This rule is not really needed anymore as setting `CSSStyleSheet.encoding` is much easier.

  Format:

      charsetrule:
          CHARSET_SYM S* STRING S* ';'

  BUT: Only valid format is (single space, double quotes!):

      @charset "ENCODING";

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation.

  `encoding`

    (DOM)The encoding information used in this @charset rule.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

### `CSSFontFaceRule`

class `cssutils.css.` `CSSFontFaceRule`(style=None, parentRule=None, parentStyleSheet=None, readonly=False)

  The CSSFontFaceRule interface represents a @font-face rule in a CSS style sheet. The @font-face rule is used to hold a set of font descriptions.

  Format:

      font_face
        : FONT_FACE_SYM S*
          '{' S* declaration [ ';' S* declaration ]* '}' S*
        ;

  cssutils uses a `CSSStyleDeclaration` to represent the font descriptions. For validation a specific profile is used though were some properties have other valid values than when used in e.g. a `CSSStyleRule`.

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of this rule.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `style`

    (DOM) The declaration-block of this rule set, a `CSSStyleDeclaration`.

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

  `valid`

    CSSFontFace is valid if properties font-family and src are set and all properties are valid.

### `CSSImportRule`

class `cssutils.css.` `CSSImportRule`(href=None, mediaText=None, name=None, parentRule=None, parentStyleSheet=None, readonly=False)

  Represents an @import rule within a CSS style sheet. The @import rule is used to import style rules from other style sheets.

  Format:

      import
        : IMPORT_SYM S*
        [STRING|URI] S* [ medium [ COMMA S* medium]* ]? S* STRING? S* ';' S*
        ;

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of this rule.

  `href`

    Location of the style sheet to be imported.

  `media`

    (DOM) A list of media types for this rule of type `MediaList`.

  `name`

    An optional name for the imported sheet.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `styleSheet`

    (readonly) The style sheet referred to by this rule.

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

  `wellformed`

    Depending on if media is used at all.

### `CSSMediaRule`

class `cssutils.css.` `CSSMediaRule`(mediaText='all', name=None, parentRule=None, parentStyleSheet=None, readonly=False)

  Objects implementing the CSSMediaRule interface can be identified by the MEDIA_RULE constant. On these objects the type attribute must return the value of that constant.

  Format:

      : MEDIA_SYM S* medium [ COMMA S* medium ]*

          STRING? # the name

      LBRACE S* ruleset* '}' S*;

  `cssRules`
    All Rules in this media rule, a `CSSRuleList`.
  `add`(rule)

    Add rule to end of this mediarule. Same as `insertRule()`.

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of this rule.

  `deleteRule`(index)

    Delete the rule at index from the media block.

    Parameters: | index – The index of the rule to be removed from the media block’s rule list. For an index < 0 no `IndexSizeErr` is raised but rules for normal Python lists are used. E.g. `deleteRule(-1)` removes the last rule in cssRules. index may also be a CSSRule object which will then be removed from the media block.
    Exceptions : | `IndexSizeErr`: Raised if the specified index does not correspond to a rule in the media rule list. `NoModificationAllowedErr`: Raised if this media rule is readonly.

  `insertRule`(rule, index=None)

    Insert rule into the media block.

    Parameters: | rule – the parsable text representing the rule to be inserted. For rule sets this contains both the selector and the style declaration. For at-rules, this specifies both the at-identifier and the rule content. cssutils also allows rule to be a valid `CSSRule` object. index – before the specified rule will be inserted. If the specified index is equal to the length of the media blocks’s rule collection, the rule will be added to the end of the media block. If index is not given or None rule will be appended to rule list.
    Returns: | the index within the media block’s rule collection of the newly inserted rule.
    Exceptions : | `HierarchyRequestErr`: Raised if the rule cannot be inserted at the specified index, e.g., if an @import rule is inserted after a standard rule set or other at-rule. `IndexSizeErr`: Raised if the specified index is not a valid insertion point. `NoModificationAllowedErr`: Raised if this media rule is readonly. `SyntaxErr`: Raised if the specified rule has a syntax error and is unparsable.

  `media`

    (DOM) A list of media types for this rule of type `MediaList`.

  `name`

    An optional name for this media rule.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

### `CSSNamespaceRule`

class `cssutils.css.` `CSSNamespaceRule`(namespaceURI=None, prefix=None, cssText=None, parentRule=None, parentStyleSheet=None, readonly=False)

  Represents an @namespace rule within a CSS style sheet.

  The @namespace at-rule declares a namespace prefix and associates it with a given namespace (a string). This namespace prefix can then be used in namespace-qualified names such as those described in the Selectors Module [SELECT] or the Values and Units module [CSS3VAL].

  Dealing with these rules directly is not needed anymore, easier is the use of `cssutils.css.CSSStyleSheet.namespaces`.

  Format:

      namespace
        : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
        ;
      namespace_prefix
        : IDENT
        ;

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of this rule.

  `namespaceURI`

    URI (handled as simple string) of the defined namespace.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `prefix`

    Prefix used for the defined namespace.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

### `CSSPageRule`

class `cssutils.css.` `CSSPageRule`(selectorText=None, style=None, parentRule=None, parentStyleSheet=None, readonly=False)

  The CSSPageRule interface represents a @page rule within a CSS style sheet. The @page rule is used to specify the dimensions, orientation, margins, etc. of a page box for paged media.

  Format:

      page
        PAGE_SYM S* IDENT? pseudo_page? S*
          '{' S* declaration [ ';' S* declaration ]* '}' S*
        ;
      pseudo_page
        ':' [ "left" | "right" | "first" ]
        ;

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of this rule.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `selectorText`

    (DOM) The parsable textual representation of the page selector for the rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `style`

    (DOM) The declaration-block of this rule set, a `CSSStyleDeclaration`.

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

### `CSSStyleRule`

class `cssutils.css.` `CSSStyleRule`(selectorText=None, style=None, parentRule=None, parentStyleSheet=None, readonly=False)

  The CSSStyleRule object represents a ruleset specified (if any) in a CSS style sheet. It provides access to a declaration block as well as to the associated group of selectors.

  Format:

      : selector [ COMMA S* selector ]*
      LBRACE S* declaration [ ';' S* declaration ]* '}' S*
      ;

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of this rule.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `selectorList`

    The SelectorList of this rule.

  `selectorText`

    (DOM) The textual representation of the selector for the rule set.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `style`

    (DOM) The declaration-block of this rule set.

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

### `CSSVariablesRule`

class `cssutils.css.` `CSSVariablesRule`(mediaText=None, variables=None, parentRule=None, parentStyleSheet=None, readonly=False)

  The CSSVariablesRule interface represents a @variables rule within a CSS style sheet. The @variables rule is used to specify variables.

  cssutils uses a `CSSVariablesDeclaration` to represent the variables.

  Format:

      variables
          VARIABLES_SYM S* medium [ COMMA S* medium ]* LBRACE S*
          variableset* '}' S*
          ;

  for variableset see `cssutils.css.CSSVariablesDeclaration`

  Media are not implemented. Reason is that cssutils is using CSS variables in a kind of preprocessing and therefor no media information is available at this stage. For now do not use media!

  Example:

      @variables {
        CorporateLogoBGColor: #fe8d12;
      }

      div.logoContainer {
        background-color: var(CorporateLogoBGColor);
      }

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    (DOM) The parsable textual representation of this rule.

  `media`

    NOT IMPLEMENTED! As cssutils resolves variables during serializing media information is lost.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

  `valid`

    NOT IMPLEMTED REALLY (TODO)

  `variables`

    (DOM) The variables of this rule set, a `cssutils.css.CSSVariablesDeclaration`.

### `CSSComment`

class `cssutils.css.` `CSSComment`(cssText=None, parentRule=None, parentStyleSheet=None, readonly=False)

  Represents a CSS comment (cssutils only).

  Format:

      /*...*/

  `atkeyword`

    Literal keyword of an @rule (e.g. `@IMport`).

  `cssText`

    The parsable textual representation of this rule.

  `parent`

    The Parent Node of this CSSRule or None.

  `parentRule`

    If this rule is contained inside another rule (e.g. a style rule inside an @media block), this is the containing rule. If this rule is not nested inside any other rules, this returns None.

  `parentStyleSheet`

    The style sheet that contains this rule.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    The type of this rule, as defined by a CSSRule type constant.

  `typeString`

    Descriptive name of this rule’s type.

## Selector related classes: `SelectorList` and `Selector`

### `SelectorList`

class `cssutils.css.` `SelectorList`(selectorText=None, parentRule=None, readonly=False)

  A list of `Selector` objects of a `CSSStyleRule`.

  `append`(newSelector)

    Same as `appendSelector()`.

  `appendSelector`(newSelector)

    Append newSelector to this list (a string will be converted to a `Selector`).

    Parameters: | newSelector – comma-separated list of selectors (as a single string) or a tuple of (newSelector, dict-of-namespaces)
    Returns: | New `Selector` or `None` if newSelector is not wellformed.
    Exceptions : | `NamespaceErr`: Raised if the specified selector uses an unknown namespace prefix. `SyntaxErr`: Raised if the specified CSS string value has a syntax error and is unparsable. `NoModificationAllowedErr`: Raised if this rule is readonly.

  `length`

    The number of `Selector` objects in the list.

  `parentRule`

    (DOM) The CSS rule that contains this SelectorList or `None` if this SelectorList is not attached to a CSSRule.

  `selectorText`

    (cssutils) The textual representation of the selector for a rule set.

### `Selector`

class `cssutils.css.` `Selector`(selectorText=None, parent=None, readonly=False)

  (cssutils) a single selector in a `SelectorList` of a `CSSStyleRule`.

  Format:

      # implemented in SelectorList
      selectors_group
        : selector [ COMMA S* selector ]*
        ;

      selector
        : simple_selector_sequence [ combinator simple_selector_sequence ]*
        ;

      combinator
        /* combinators can be surrounded by white space */
        : PLUS S* | GREATER S* | TILDE S* | S+
        ;

      simple_selector_sequence
        : [ type_selector | universal ]
          [ HASH | class | attrib | pseudo | negation ]*
        | [ HASH | class | attrib | pseudo | negation ]+
        ;

      type_selector
        : [ namespace_prefix ]? element_name
        ;

      namespace_prefix
        : [ IDENT | '*' ]? '|'
        ;

      element_name
        : IDENT
        ;

      universal
        : [ namespace_prefix ]? '*'
        ;

      class
        : '.' IDENT
        ;

      attrib
        : '[' S* [ namespace_prefix ]? IDENT S*
              [ [ PREFIXMATCH |
                  SUFFIXMATCH |
                  SUBSTRINGMATCH |
                  '=' |
                  INCLUDES |
                  DASHMATCH ] S* [ IDENT | STRING ] S*
              ]? ']'
        ;

      pseudo
        /* '::' starts a pseudo-element, ':' a pseudo-class */
        /* Exceptions: :first-line, :first-letter, :before and :after. */
        /* Note that pseudo-elements are restricted to one per selector and */
        /* occur only in the last simple_selector_sequence. */
        : ':' ':'? [ IDENT | functional_pseudo ]
        ;

      functional_pseudo
        : FUNCTION S* expression ')'
        ;

      expression
        /* In CSS3, the expressions are identifiers, strings, */
        /* or of the form "an+b" */
        : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
        ;

      negation
        : NOT S* negation_arg S* ')'
        ;

      negation_arg
        : type_selector | universal | HASH | class | attrib | pseudo
        ;

  `element`

    Effective element target of this selector.

  `parent`

    (DOM) The SelectorList that contains this Selector or None if this Selector is not attached to a SelectorList.

  `parentList`

    DEPRECATED, see property parent instead

  `selectorText`

    (DOM) The parsable textual representation of the selector.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `specificity`

    Specificity of this selector (READONLY). Tuple of (a, b, c, d) where:

    a
      presence of style in document, always 0 if not used on a document
    b
      number of ID selectors
    c
      number of .class selectors
    d
      number of Element (type) selectors

## Style related classes: `CSSStyleDeclaration`, `Property`, values etc

### `CSSVariablesDeclaration`

class `cssutils.css.` `CSSVariablesDeclaration`(cssText=u'', parentRule=None, readonly=False)

  The CSSVariablesDeclaration interface represents a single block of variable declarations.

  `cssText`

    (DOM) A parsable textual representation of the declaration block excluding the surrounding curly braces.

  `getVariableValue`(variableName)

    Used to retrieve the value of a variable if it has been explicitly set within this variable declaration block.

    Parameters: | variableName – The name of the variable.
    Returns: | the value of the variable if it has been explicitly set in this variable declaration block. Returns the empty string if the variable has not been set.

  `item`(index)

    Used to retrieve the variables that have been explicitly set in this variable declaration block. The order of the variables retrieved using this method does not have to be the order in which they were set. This method can be used to iterate over all variables in this variable declaration block.

    Parameters: | index – of the variable name to retrieve, negative values behave like negative indexes on Python lists, so -1 is the last element
    Returns: | The name of the variable at this ordinal position. The empty string if no variable exists at this position.

  `keys`()

    Analoguous to standard dict returns variable names which are set in this declaration.

  `length`

    The number of variables that have been explicitly set in this variable declaration block. The range of valid indices is 0 to length-1 inclusive.

  `parentRule`

    (DOM) The CSS rule that contains this declaration block or None if this block is not attached to a CSSRule.

  `removeVariable`(variableName)

    Used to remove a variable if it has been explicitly set within this variable declaration block.

    Parameters: | variableName – The name of the variable.
    Returns: | the value of the variable if it has been explicitly set for this variable declaration block. Returns the empty string if the variable has not been set.
    Exceptions : | `NoModificationAllowedErr`: Raised if this declaration is readonly is readonly.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `setVariable`(variableName, value)

    Used to set a variable value within this variable declaration block.

    Parameters: | variableName – The name of the CSS variable. value – The new value of the variable, may also be a PropertyValue object.
    Exceptions : | `SyntaxErr`: Raised if the specified value has a syntax error and is unparsable. `NoModificationAllowedErr`: Raised if this declaration is readonly or the property is readonly.

### `CSSStyleDeclaration`

class `cssutils.css.` `CSSStyleDeclaration`(cssText=u'', parentRule=None, readonly=False)

  The CSSStyleDeclaration class represents a single CSS declaration block. This class may be used to determine the style properties currently set in a block or to set style properties explicitly within the block.

  While an implementation may not recognize all CSS properties within a CSS declaration block, it is expected to provide access to all specified properties in the style sheet through the CSSStyleDeclaration interface. Furthermore, implementations that support a specific level of CSS should correctly handle CSS shorthand properties for that level. For a further discussion of shorthand properties, see the CSS2Properties interface.

  Additionally the CSS2Properties interface is implemented.

  $css2propertyname

    All properties defined in the CSS2Properties class are available as direct properties of CSSStyleDeclaration with their respective DOM name, so e.g. `fontStyle` for property ‘font-style’.

    These may be used as:

        >>> style = CSSStyleDeclaration(cssText='color: red')
        >>> style.color = 'green'
        >>> print style.color
        green
        >>> del style.color
        >>> print style.color

  Format:

      [Property: Value Priority?;]* [Property: Value Priority?]?

  `children`()

    Generator yielding any known child in this declaration including all properties, comments or CSSUnknownrules.

  `cssText`

    (DOM) A parsable textual representation of the declaration block excluding the surrounding curly braces.

  `getCssText`(separator=None)

    Returns: |

    serialized property cssText, each property separated by given separator which may e.g. be `u''` to be able to use cssText directly in an HTML style attribute. `;` is part of each property (except the last one) and cannot be set with separator!

  `getProperties`(name=None, all=False)

    Parameters: | name – optional name of properties which are requested. Only properties with this always normalized name are returned. If name is `None` all properties are returned (at least one for each set name depending on parameter all). all – if `False` (DEFAULT) only the effective properties are returned. If name is given a list with only one property is returned. if `True` all properties including properties set multiple times with different values or priorities for different UAs are returned. The order of the properties is fully kept as in the original stylesheet.
    Returns: | a list of `Property` objects set in this declaration.

  `getProperty`(name, normalize=True)

    Parameters: | name – of the CSS property, always lowercase (even if not normalized) normalize – if `True` (DEFAULT) name will be normalized (lowercase, no simple escapes) so “color”, “COLOR” or “Color” will all be equivalent If `False` may return NOT the effective value but the effective for the unnormalized name.
    Returns: | the effective `Property` object.

  `getPropertyCSSValue`(name, normalize=True)

    Parameters: | name – of the CSS property, always lowercase (even if not normalized) normalize – if `True` (DEFAULT) name will be normalized (lowercase, no simple escapes) so “color”, “COLOR” or “Color” will all be equivalent If `False` may return NOT the effective value but the effective for the unnormalized name.
    Returns: | `CSSValue`, the value of the effective property if it has been explicitly set for this declaration block.

    (DOM) Used to retrieve the object representation of the value of a CSS property if it has been explicitly set within this declaration block. Returns None if the property has not been set.

    (This method returns None if the property is a shorthand property. Shorthand property values can only be accessed and modified as strings, using the getPropertyValue and setProperty methods.)

    cssutils currently always returns a CSSValue if the property is set.

    for more on shorthand properties see
      http://www.dustindiaz.com/css-shorthand/
  `getPropertyPriority`(name, normalize=True)

    Parameters: | name – of the CSS property, always lowercase (even if not normalized) normalize – if `True` (DEFAULT) name will be normalized (lowercase, no simple escapes) so “color”, “COLOR” or “Color” will all be equivalent If `False` may return NOT the effective value but the effective for the unnormalized name.
    Returns: | the priority of the effective CSS property (e.g. the “important” qualifier) if the property has been explicitly set in this declaration block. The empty string if none exists.

  `getPropertyValue`(name, normalize=True)

    Parameters: | name – of the CSS property, always lowercase (even if not normalized) normalize – if `True` (DEFAULT) name will be normalized (lowercase, no simple escapes) so “color”, “COLOR” or “Color” will all be equivalent If `False` may return NOT the effective value but the effective for the unnormalized name.
    Returns: | the value of the effective property if it has been explicitly set for this declaration block. Returns the empty string if the property has not been set.

  `item`(index)

    (DOM) Retrieve the properties that have been explicitly set in this declaration block. The order of the properties retrieved using this method does not have to be the order in which they were set. This method can be used to iterate over all properties in this declaration block.

    Parameters: | index – of the property to retrieve, negative values behave like negative indexes on Python lists, so -1 is the last element
    Returns: | the name of the property at this ordinal position. The empty string if no property exists at this position.

    ATTENTION: Only properties with different names are counted. If two properties with the same name are present in this declaration only the effective one is included.

    `item()` and `length` work on the same set here.

  `keys`()

    Analoguous to standard dict returns property names which are set in this declaration.

  `length`

    (DOM) The number of distinct properties that have been explicitly in this declaration block. The range of valid indices is 0 to length-1 inclusive. These are properties with a different `name` only. `item()` and `length` work on the same set here.

  `parentRule`

    (DOM) The CSS rule that contains this declaration block or None if this CSSStyleDeclaration is not attached to a CSSRule.

  `removeProperty`(name, normalize=True)

    (DOM) Used to remove a CSS property if it has been explicitly set within this declaration block.

    Parameters: | name – of the CSS property normalize – if `True` (DEFAULT) name will be normalized (lowercase, no simple escapes) so “color”, “COLOR” or “Color” will all be equivalent. The effective Property value is returned and all Properties with `Property.name == name` are removed. If `False` may return NOT the effective value but the effective for the unnormalized name only. Also only the Properties with the literal name name are removed.
    Returns: | the value of the property if it has been explicitly set for this declaration block. Returns the empty string if the property has not been set or the property name does not correspond to a known CSS property
    Exceptions : | `NoModificationAllowedErr`: Raised if this declaration is readonly or the property is readonly.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `setProperty`(name, value=None, priority=u'', normalize=True)

    (DOM) Set a property value and priority within this declaration block.

    Parameters: | name – of the CSS property to set (in W3C DOM the parameter is called “propertyName”), always lowercase (even if not normalized) If a property with this name is present it will be reset. cssutils also allowed name to be a `Property` object, all other parameter are ignored in this case value – the new value of the property, ignored if name is a Property. priority – the optional priority of the property (e.g. “important”), ignored if name is a Property. normalize – if True (DEFAULT) name will be normalized (lowercase, no simple escapes) so “color”, “COLOR” or “Color” will all be equivalent
    Exceptions : | `SyntaxErr`: Raised if the specified value has a syntax error and is unparsable. `NoModificationAllowedErr`: Raised if this declaration is readonly or the property is readonly.

The official DOM provides no method to obtain all values set for a property. Cssutils from 0.9.4 implements the additional method `getProperties()`, example:

    >>> cssText = '''background: white url(paper.png) scroll; /* for all UAs */
    ... background: white url(ledger.png) fixed; /* for UAs that do fixed backgrounds */
    ... '''
    >>> # omit comments for this example
    >>> cssutils.ser.prefs.keepComments = False
    >>> style = cssutils.css.CSSStyleDeclaration(cssText=cssText)
    >>> print style.cssText
    background: white url(paper.png) scroll;
    background: white url(ledger.png) fixed;
    >>> # work with properties:
    >>> proplist = style.getProperties('background', all=True)
    >>> proplist
    [cssutils.css.Property(name='background', value=u'white url(paper.png) scroll', priority=u''), cssutils.css.Property(name='background', value=u'white url(ledger.png) fixed', priority=u'')]
    >>> for prop in proplist: print prop.value
    white url(paper.png) scroll
    white url(ledger.png) fixed
    >>> # overwrite the current property, to overwrite all iterate over proplist
    >>> style['background'] = ('red', '!important')
    >>> # importance in DOM ist 'important' but '!important' works too
    >>> print style['background'], style.getPropertyPriority('background')
    red important
    >>> print style.cssText
    background: white url(paper.png) scroll;
    background: red !important;
    >>> # output only "effective" properties
    >>> cssutils.ser.prefs.keepAllProperties = False
    >>> print style.cssText
    background: red !important;

### `Property`

class `cssutils.css.` `Property`(name=None, value=None, priority=u'', _mediaQuery=False, parent=None)

  A CSS property in a StyleDeclaration of a CSSStyleRule (cssutils).

  Format:

      property = name
        : IDENT S*
        ;

      expr = value
        : term [ operator term ]*
        ;
      term
        : unary_operator?
          [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* |
            ANGLE S* | TIME S* | FREQ S* | function ]
        | STRING S* | IDENT S* | URI S* | hexcolor
        ;
      function
        : FUNCTION S* expr ')' S*
        ;
      /*
       * There is a constraint on the color that it must
       * have either 3 or 6 hex-digits (i.e., [0-9a-fA-F])
       * after the "#"; e.g., "#000" is OK, but "#abcd" is not.
       */
      hexcolor
        : HASH S*
        ;

      prio
        : IMPORTANT_SYM S*
        ;

  `cssText`

    A parsable textual representation.

  `cssValue`

    (DEPRECATED) Use `property.propertyValue` instead.

  `literalname`

    Readonly literal (not normalized) name of this property

  `literalpriority`

    Readonly literal (not normalized) priority of this property

  `name`

    Name of this property.

  `parent`

    The Parent Node (normally a CSSStyledeclaration) of this Property

  `priority`

    Priority of this property.

  `propertyValue`

    (cssutils) PropertyValue object of property

  `valid`

    Check if value of this property is valid in the properties context.

  `validate`()

    Validate value against profiles which are checked dynamically. properties in e.g. @font-face rules are checked against `cssutils.profile.CSS3_FONT_FACE` only.

    For each of the following cases a message is reported:

    - INVALID (so the property is known but not valid)

        `ERROR Property: Invalid value for "{PROFILE-1[/PROFILE-2...]" property: ...`

    - VALID but not in given profiles or defaultProfiles

        `WARNING Property: Not valid for profile "{PROFILE-X}" but valid "{PROFILE-Y}" property: ...`

    - VALID in current profile

        `DEBUG Found valid "{PROFILE-1[/PROFILE-2...]" property...`

    - UNKNOWN property

        `WARNING Unknown Property name...` is issued

    so for example:

        cssutils.log.setLevel(logging.DEBUG)
        parser = cssutils.CSSParser()
        s = parser.parseString('''body {
            unknown-property: x;
            color: 4;
            color: rgba(1,2,3,4);
            color: red
        }''')

        # Log output:

        WARNING Property: Unknown Property name. [2:9: unknown-property]
        ERROR   Property: Invalid value for "CSS Color Module Level 3/CSS Level 2.1" property: 4 [3:9: color]
        DEBUG   Property: Found valid "CSS Color Module Level 3" value: rgba(1, 2, 3, 4) [4:9: color]
        DEBUG   Property: Found valid "CSS Level 2.1" value: red [5:9: color]

    and when setting an explicit default profile:

        cssutils.profile.defaultProfiles = cssutils.profile.CSS_LEVEL_2
        s = parser.parseString('''body {
            unknown-property: x;
            color: 4;
            color: rgba(1,2,3,4);
            color: red
        }''')

        # Log output:

        WARNING Property: Unknown Property name. [2:9: unknown-property]
        ERROR   Property: Invalid value for "CSS Color Module Level 3/CSS Level 2.1" property: 4 [3:9: color]
        WARNING Property: Not valid for profile "CSS Level 2.1" but valid "CSS Color Module Level 3" value: rgba(1, 2, 3, 4)  [4:9: color]
        DEBUG   Property: Found valid "CSS Level 2.1" value: red [5:9: color]

  `value`

    The textual value of this Properties propertyValue.

### Values

cssutils 0.9.8 features a new and hopefully simplified but more consistent API which also will hopefully be more stable in API and code. Please check out the development, alpha and beta versions of release 0.9.8 and report any shortcomings you may see or any special API requests you’d like to see in the new API.

A simple example:

      >>> css = 'normal 1em/5 Arial, sans-serif, url(example.gif), func(1,2/*comm*/)'
      >>> pv = cssutils.css.PropertyValue(css)
      >>> print pv.cssText
      >>> for i, v in enumerate(pv):
      >>>     print i, v
      normal 1em/5 Arial, sans-serif, url(example.gif), func(1, 2 /*comm*/)
      0 <cssutils.css.Value object type=IDENT value='normal' cssText=u'normal' at ...>
      1 <cssutils.css.DimensionValue object type=DIMENSION value=1 dimension='em' cssText=u'1em' at ...>
      2 <cssutils.css.DimensionValue object type=NUMBER value=5 dimension=None cssText=u'5' at ...>
      3 <cssutils.css.Value object type=IDENT value='Arial' cssText=u'Arial' at ...>
      4 <cssutils.css.Value object type=IDENT value='sans-serif' cssText=u'sans-serif' at...>
      5 <cssutils.css.URIValue object type=URI value='example.gif' uri='example.gif' cssText=u'url(example.gif)' at ...>
      6 <cssutils.css.CSSFunction object type=FUNCTION value=u'func(1, 2)' cssText=u'func(1, 2 /*comm*/)' at ...>

#### `PropertyValue`

class `cssutils.css.` `PropertyValue`(cssText=None, parent=None, readonly=False)

  An unstructured list like holder for all values defined for a `Property`. Contains `Value` or subclass objects. Currently there is no access to the combinators of the defined values which might simply be space or comma or slash.

  You may:

  - iterate over all contained Value objects (not the separators like `,`, `/` or `` `` though!)
  - get a Value item by index or use `PropertyValue[index]`
  - find out the number of values defined (unstructured)
  `cssText`

    A string representation of the current value.

  `item`(index)

    The value at position index. Alternatively simple use `PropertyValue[index]`.

    Parameters: | index – the parsable cssText of the value
    Exceptions : | `IndexError`: Raised if index if out of bounds

  `length`

    Number of values set.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `value`

    A string representation of the current value without any comments used for validation.

#### `Value`

class `cssutils.css.` `Value`(cssText=None, parent=None, readonly=False)

  Represents a single CSS value. For now simple values of IDENT, STRING, or UNICODE-RANGE values are represented directly as Value objects. Other values like e.g. FUNCTIONs are represented by subclasses with an extended API.

  `cssText`

    String value of this value.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    Type of this value, for now the production type like e.g. DIMENSION or STRING. All types are defined as constants in `Value`.

  `value`

    Actual value if possible: An int or float or else a string

#### `ColorValue`

class `cssutils.css.` `ColorValue`(cssText=None, parent=None, readonly=False)

  A color value like rgb(), rgba(), hsl(), hsla() or #rgb, #rrggbb

  TODO: Color Keywords

  `alpha`

    alpha part as float between 0.0 and 1.0

  `blue`

    blue part as integer between 0 and 255

  `colorType`

    IDENT (red), HASH (#f00) or FUNCTION (rgb(255, 0, 0).

  `cssText`

    String value of this value.

  `green`

    green part as integer between 0 and 255

  `name`

    Name of the color if known (in ColorValue.COLORS) else None

  `red`

    red part as integer between 0 and 255

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    Type is fixed to Value.COLOR_VALUE.

  `value`

    Same as cssText but without comments.

#### `DimensionValue`

class `cssutils.css.` `DimensionValue`(cssText=None, parent=None, readonly=False)

  A numerical value with an optional dimenstion like e.g. “px” or “%”.

  Covers DIMENSION, PERCENTAGE or NUMBER values.

  `cssText`

    String value of this value including dimension.

  `dimension`

    Dimension if a DIMENSION or PERCENTAGE value, else None

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    Type of this value, for now the production type like e.g. DIMENSION or STRING. All types are defined as constants in `Value`.

  `value`

    Actual value if possible: An int or float or else a string

#### `URIValue`

class `cssutils.css.` `URIValue`(cssText=None, parent=None, readonly=False)

  An URI value like `url(example.png)`.

  `absoluteUri`

    Actual URL, made absolute if possible, else same as uri.

  `cssText`

    String value of this value.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    Type of this value, for now the production type like e.g. DIMENSION or STRING. All types are defined as constants in `Value`.

  `uri`

    Actual URL without delimiters or the empty string

  `value`

    Actual value if possible: An int or float or else a string

#### `CSSFunction`

class `cssutils.css.` `CSSFunction`(cssText=None, parent=None, readonly=False)

  A function value.

  `cssText`

    String value of this value.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    Type is fixed to Value.FUNCTION.

  `value`

    Same as cssText but without comments.

#### `MSValue`

was `ExpressionValue` until 0.9.7.

class `cssutils.css.` `MSValue`(cssText=None, parent=None, readonly=False)

  An IE specific Microsoft only function value which is much looser in what is syntactically allowed.

  `cssText`

    String value of this value.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    Type is fixed to Value.FUNCTION.

  `value`

    Same as cssText but without comments.

#### `CSSVariable`

class `cssutils.css.` `CSSVariable`(cssText=None, parent=None, readonly=False)

  The CSSVariable represents a CSS variables like `var(varname)`.

  A variable has a (nonnormalized!) name and a value which is tried to be resolved from any available CSSVariablesRule definition.

  `cssText`

    String representation of variable.

  `name`

    The name identifier of this variable referring to a value in a `cssutils.css.CSSVariablesDeclaration`.

  `seq`

    Internal readonly attribute, DO NOT USE!

  `type`

    Type is fixed to Value.VARIABLE.

  `value`

    The resolved actual value or None.

### removed classes

- `CSSValue`
- `CSSPrimitiveValue`
- `CSSValueList`

## Additional Info

Some classes in this package support standard Python idioms like iteration on certain attributes:

    >>> import cssutils
    >>> sheet = cssutils.css.CSSStyleSheet()
    >>> sheet.cssText = '@charset "ascii";a { color: green }'
    >>> for rule in sheet:
    ...     print rule
    ...
    <cssutils.css.CSSCharsetRule object encoding='ascii' at 0x2ce7
    <cssutils.css.CSSStyleRule object selector=u'a' style=u'color:
    s=<cssutils.util._Namespaces object at 0x02CE7B30> at 0x2ce7d3

`for in` is supported by `CSSStyleSheet` and `CSSMediaRule` (iterating over the contained `CSSRule` objects, `CSSStyleDeclaration` (over the names of the contained `Property` objects), `CSSValueList` (over the `CSSValue` objects in the list).

### Navigation

- index
- modules |
- next |
- previous |
- cssutils 0.9.8 documentation »