File: first_steps.rst

package info (click to toggle)
python-tinycss2 1.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 844 kB
  • sloc: python: 2,811; makefile: 21
file content (85 lines) | stat: -rw-r--r-- 2,383 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
First Steps
===========


Installation
------------

The easiest way to use tinycss2 is to install it in a Python `virtual
environment`_. When your virtual environment is activated, you can then install
tinycss2 with pip_::

    pip install tinycss2

This will also automatically install tinycss2’s only dependency, webencodings_.
tinycss2 and webencodings both only contain Python code and should work on any
Python implementation.

tinycss2 also is packaged for many Linux distributions (Debian, Ubuntu, Fedora,
Archlinux, Gentoo…).

.. _virtual environment: https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/
.. _pip: https://pip.pypa.io/
.. _webencodings: https://pythonhosted.org/webencodings/


CSS Parsing
-----------

tinycss2’s main goal is to parse CSS and return corresponding Python
objects. Parsing CSS is done using the :func:`~tinycss2.parse_stylesheet`
function.

.. code-block:: python

   import tinycss2

   rules = tinycss2.parse_stylesheet('#cell div { width: 50% }')

   print(rules)
   # [<QualifiedRule … { … }>]
   rule = rules[0]

   print(rule.prelude)
   # [
   #     <HashToken #cell>,
   #     <WhitespaceToken>,
   #     <IdentToken div>,
   #     <WhitespaceToken>,
   # ]

   print(rule.content)
   # [
   #     <WhitespaceToken>,
   #     <IdentToken width>,
   #     <LiteralToken :>,
   #     <WhitespaceToken>,
   #     <PercentageToken 50%>,
   #     <WhitespaceToken>,
   # ]

In this example, you can see that ``'body div { width: 50% }'`` is a list of
one CSS `qualified rule`_. This rule contains a prelude (a CSS selector) and
some content (one CSS property with its value).

The prelude contains 4 parts, called tokens_:

- a hash token (``#cell``),
- a whitespace token (between ``#cell`` and ``div``),
- an identifier token (``div``),
- a whitespace token (after ``div``).

The content, that is between ``{`` and ``}``, contains 6 tokens:

- a whitespace token (before ``width``),
- an identifier token (``width``),
- a literal token (``:``),
- a whitespace token (between ``:`` and ``50%``),
- a percentage token (``50%``),
- a whitespace token (after ``50%``).

You can find what you can do with this rule and these tokens on the
:ref:`Common Use Cases` page.

.. _qualified rule: https://www.w3.org/TR/css-syntax-3/#qualified-rule
.. _tokens: https://www.w3.org/TR/css-syntax-3/#tokenization