or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

css-rules.mdindex.mdparsing.mdselectors.mdserialization.mdstyle-declarations.mdstylesheets.mdutilities.md

style-declarations.mddocs/

0

# Style Declarations

1

2

Manage CSS property declarations with validation, shorthand expansion, value parsing, and complete support for CSS property manipulation within rules.

3

4

## Capabilities

5

6

### CSSStyleDeclaration Class

7

8

Container for CSS property declarations implementing DOM Level 2 CSSStyleDeclaration interface.

9

10

```python { .api }

11

class CSSStyleDeclaration:

12

"""

13

CSS property declarations container implementing DOM Level 2 CSSStyleDeclaration.

14

15

Constructor:

16

CSSStyleDeclaration(cssText='', parentRule=None, readonly=False, validating=True)

17

18

Parameters:

19

- cssText (str): Initial CSS declarations text

20

- parentRule: Parent CSS rule that owns this declaration

21

- readonly (bool): Whether declarations can be modified

22

- validating (bool): Whether to validate property names and values

23

"""

24

25

# Properties

26

cssText: str # Complete CSS text of all declarations

27

length: int # Number of property declarations

28

parentRule # Parent CSS rule

29

30

# Property Access Methods

31

def getPropertyValue(propertyName):

32

"""

33

Get property value by name.

34

35

Parameters:

36

- propertyName (str): CSS property name

37

38

Returns:

39

str: Property value, or empty string if not set

40

"""

41

42

def getPropertyPriority(propertyName):

43

"""

44

Get property priority (!important).

45

46

Parameters:

47

- propertyName (str): CSS property name

48

49

Returns:

50

str: 'important' if !important is set, empty string otherwise

51

"""

52

53

def setProperty(propertyName, value, priority=''):

54

"""

55

Set property value and priority.

56

57

Parameters:

58

- propertyName (str): CSS property name

59

- value (str): CSS property value

60

- priority (str): Priority ('important' or empty string)

61

"""

62

63

def removeProperty(propertyName):

64

"""

65

Remove property from declarations.

66

67

Parameters:

68

- propertyName (str): CSS property name to remove

69

70

Returns:

71

str: Previous value of removed property

72

"""

73

74

def item(index):

75

"""

76

Get property name at index.

77

78

Parameters:

79

- index (int): Property index (0-based)

80

81

Returns:

82

str: Property name at index

83

"""

84

85

# Property Collection Methods

86

def getProperties(all=False):

87

"""

88

Get list of Property objects.

89

90

Parameters:

91

- all (bool): If True, include all properties including duplicates and invalid

92

93

Returns:

94

list: List of Property objects

95

"""

96

97

def keys():

98

"""

99

Get list of property names.

100

101

Returns:

102

list: List of property names

103

"""

104

105

# Iteration Support

106

def __getitem__(index):

107

"""Get property name by index"""

108

109

def __len__():

110

"""Get number of properties"""

111

112

def __iter__():

113

"""Iterator over property names"""

114

115

# CSS Text Methods

116

@property

117

def cssText():

118

"""Get/set complete CSS declarations text"""

119

120

@cssText.setter

121

def cssText(cssText):

122

"""Set declarations from CSS text"""

123

```

124

125

### Property Class

126

127

Individual CSS property with name, value, and priority.

128

129

```python { .api }

130

class Property:

131

"""

132

Individual CSS property within a CSSStyleDeclaration.

133

"""

134

135

# Properties

136

name: str # Property name (normalized)

137

value: str # Property value text

138

priority: str # Priority ('important' or empty)

139

propertyValue: 'PropertyValue' # Parsed property value object

140

141

# Methods

142

@property

143

def name():

144

"""Get/set property name"""

145

146

@name.setter

147

def name(name):

148

"""Set property name with normalization"""

149

150

@property

151

def value():

152

"""Get/set property value text"""

153

154

@value.setter

155

def value(value):

156

"""Set property value with parsing"""

157

158

@property

159

def priority():

160

"""Get/set property priority"""

161

162

@priority.setter

163

def priority(priority):

164

"""Set property priority ('important' or empty)"""

165

```

166

167

### PropertyValue Class

168

169

Structured representation of CSS property values with individual value components.

170

171

```python { .api }

172

class PropertyValue:

173

"""

174

Container for CSS property values with structured access to components.

175

"""

176

177

# Properties

178

cssText: str # Complete property value text

179

length: int # Number of value components

180

181

# Value Access Methods

182

def item(index):

183

"""

184

Get value component at index.

185

186

Parameters:

187

- index (int): Value component index

188

189

Returns:

190

Value: Value component at index

191

"""

192

193

def __getitem__(index):

194

"""Get value component by index"""

195

196

def __len__():

197

"""Get number of value components"""

198

199

def __iter__():

200

"""Iterator over value components"""

201

202

# Value Manipulation

203

def append(value):

204

"""Add value component to end"""

205

206

def insert(index, value):

207

"""Insert value component at index"""

208

209

def extend(values):

210

"""Add multiple value components"""

211

```

212

213

### Value Classes

214

215

Specific value types for different CSS value categories.

216

217

```python { .api }

218

class Value:

219

"""Base class for CSS values"""

220

221

# Properties

222

type: str # Value type identifier

223

cssText: str # CSS text representation

224

value: str # Normalized value

225

226

class ColorValue:

227

"""CSS color value (named colors, hex, rgb(), hsl(), etc.)"""

228

229

# Properties

230

type: str = 'COLOR'

231

red: int # Red component (0-255)

232

green: int # Green component (0-255)

233

blue: int # Blue component (0-255)

234

alpha: float # Alpha component (0.0-1.0)

235

236

class DimensionValue:

237

"""CSS dimensional value (length, percentage, angle, time, frequency)"""

238

239

# Properties

240

type: str = 'DIMENSION'

241

value: float # Numeric value

242

dimension: str # Unit (px, em, %, deg, s, Hz, etc.)

243

244

class URIValue:

245

"""CSS URI value (url())"""

246

247

# Properties

248

type: str = 'URI'

249

uri: str # URI string (without url() wrapper)

250

251

class CSSFunction:

252

"""CSS function value (rgb(), calc(), etc.)"""

253

254

# Properties

255

type: str = 'FUNCTION'

256

functionName: str # Function name

257

arguments: list # Function arguments as Value objects

258

259

class CSSVariable:

260

"""CSS variable reference (var())"""

261

262

# Properties

263

type: str = 'VARIABLE'

264

name: str # Variable name

265

fallback: 'Value' # Fallback value (optional)

266

```

267

268

## Usage Examples

269

270

### Basic Property Management

271

272

```python

273

import cssutils

274

from cssutils.css import CSSStyleDeclaration

275

276

# Create style declaration

277

style = CSSStyleDeclaration()

278

279

# Set properties

280

style.setProperty('color', 'red')

281

style.setProperty('font-size', '16px')

282

style.setProperty('margin', '10px 20px', 'important')

283

284

print(f"CSS Text: {style.cssText}")

285

print(f"Number of properties: {len(style)}")

286

287

# Get property values

288

color = style.getPropertyValue('color')

289

priority = style.getPropertyPriority('margin')

290

print(f"Color: {color}")

291

print(f"Margin priority: {priority}")

292

293

# Remove property

294

old_value = style.removeProperty('font-size')

295

print(f"Removed font-size: {old_value}")

296

```

297

298

### Working with CSS Rules

299

300

```python

301

import cssutils

302

303

# Parse CSS with properties

304

css = """

305

h1 {

306

color: #333;

307

font-size: 24px;

308

margin: 0 0 1em 0;

309

font-weight: bold !important;

310

}

311

"""

312

313

sheet = cssutils.parseString(css)

314

rule = sheet.cssRules[0] # Get first rule

315

316

# Access style declaration

317

style = rule.style

318

print(f"Rule properties: {style.cssText}")

319

320

# Iterate over properties

321

for i in range(len(style)):

322

prop_name = style.item(i)

323

prop_value = style.getPropertyValue(prop_name)

324

prop_priority = style.getPropertyPriority(prop_name)

325

print(f"{prop_name}: {prop_value} {prop_priority}")

326

327

# Modify properties

328

style.setProperty('line-height', '1.5')

329

style.setProperty('color', 'blue')

330

print(f"Modified: {style.cssText}")

331

```

332

333

### Property Object Access

334

335

```python

336

import cssutils

337

338

# Parse CSS with various properties

339

css = """

340

.example {

341

color: red;

342

background: url('bg.jpg') no-repeat center;

343

margin: 10px 20px;

344

font-weight: bold !important;

345

}

346

"""

347

348

sheet = cssutils.parseString(css)

349

style = sheet.cssRules[0].style

350

351

# Get Property objects

352

properties = style.getProperties()

353

for prop in properties:

354

print(f"Property: {prop.name}")

355

print(f" Value: {prop.value}")

356

print(f" Priority: {prop.priority}")

357

print(f" PropertyValue type: {type(prop.propertyValue)}")

358

359

# Access structured property values

360

for i, value in enumerate(prop.propertyValue):

361

print(f" Value {i}: {value.cssText} (type: {value.type})")

362

```

363

364

### Shorthand Property Handling

365

366

```python

367

import cssutils

368

369

# CSS with shorthand properties

370

css = """

371

.box {

372

margin: 10px 20px 30px 40px;

373

padding: 15px 25px;

374

border: 2px solid red;

375

background: #fff url('bg.png') no-repeat center top;

376

font: bold 16px/1.5 Arial, sans-serif;

377

}

378

"""

379

380

sheet = cssutils.parseString(css)

381

style = sheet.cssRules[0].style

382

383

# Access shorthand properties

384

print("Shorthand properties:")

385

for prop in style.getProperties():

386

print(f"{prop.name}: {prop.value}")

387

388

# Examine property value components

389

if len(prop.propertyValue) > 1:

390

print(f" Components ({len(prop.propertyValue)}):")

391

for i, value in enumerate(prop.propertyValue):

392

print(f" {i}: {value.cssText}")

393

394

# Set shorthand property

395

style.setProperty('border', '1px dashed blue')

396

print(f"\nAfter modification: {style.cssText}")

397

```

398

399

### Value Type Analysis

400

401

```python

402

import cssutils

403

from cssutils.css import ColorValue, DimensionValue, URIValue

404

405

# CSS with different value types

406

css = """

407

.demo {

408

color: rgb(255, 0, 0);

409

width: 300px;

410

height: 75%;

411

background-image: url('image.jpg');

412

transform: rotate(45deg);

413

transition-duration: 0.3s;

414

}

415

"""

416

417

sheet = cssutils.parseString(css)

418

style = sheet.cssRules[0].style

419

420

# Analyze value types

421

for prop in style.getProperties():

422

print(f"\nProperty: {prop.name}")

423

424

for value in prop.propertyValue:

425

print(f" Value: {value.cssText}")

426

print(f" Type: {value.type}")

427

428

# Handle specific value types

429

if isinstance(value, ColorValue):

430

print(f" RGB: ({value.red}, {value.green}, {value.blue})")

431

if hasattr(value, 'alpha'):

432

print(f" Alpha: {value.alpha}")

433

elif isinstance(value, DimensionValue):

434

print(f" Number: {value.value}")

435

print(f" Unit: {value.dimension}")

436

elif isinstance(value, URIValue):

437

print(f" URI: {value.uri}")

438

```

439

440

### Property Validation

441

442

```python

443

import cssutils

444

445

# Enable validation

446

parser = cssutils.CSSParser(validate=True)

447

448

# Valid CSS

449

valid_css = """

450

.valid {

451

color: red;

452

margin: 10px;

453

display: block;

454

}

455

"""

456

457

# Invalid CSS

458

invalid_css = """

459

.invalid {

460

color: notacolor;

461

margin: invalidvalue;

462

unknown-property: somevalue;

463

}

464

"""

465

466

# Parse with validation

467

print("Parsing valid CSS:")

468

valid_sheet = parser.parseString(valid_css)

469

print(f"Rules: {len(valid_sheet.cssRules)}")

470

471

print("\nParsing invalid CSS:")

472

invalid_sheet = parser.parseString(invalid_css)

473

print(f"Rules: {len(invalid_sheet.cssRules)}")

474

475

# Check individual properties

476

if invalid_sheet.cssRules:

477

style = invalid_sheet.cssRules[0].style

478

for prop in style.getProperties(all=True): # Include invalid properties

479

print(f"Property: {prop.name} = {prop.value}")

480

```

481

482

### CSS Variables Support

483

484

```python

485

import cssutils

486

487

# CSS with custom properties (variables)

488

css = """

489

:root {

490

--main-color: #333;

491

--main-font: Arial, sans-serif;

492

--spacing: 20px;

493

}

494

495

.component {

496

color: var(--main-color);

497

font-family: var(--main-font);

498

margin: var(--spacing);

499

padding: var(--spacing, 10px); /* with fallback */

500

}

501

"""

502

503

sheet = cssutils.parseString(css)

504

505

# Access variable declarations

506

for rule in sheet:

507

if rule.type == rule.STYLE_RULE:

508

print(f"Selector: {rule.selectorText}")

509

style = rule.style

510

511

for prop in style.getProperties():

512

print(f" {prop.name}: {prop.value}")

513

514

# Look for variable references

515

for value in prop.propertyValue:

516

if hasattr(value, 'type') and value.type == 'VARIABLE':

517

print(f" Variable: {value.name}")

518

if hasattr(value, 'fallback') and value.fallback:

519

print(f" Fallback: {value.fallback.cssText}")

520

```