CSS DSL

CSS DSL extends HTML DSL and allows you to author stylesheets in Kotlin by using the kotlin-css wrapper.

tip

CSS DSL - 图1

Learn how to serve stylesheets as static content from Serving Static Content.

Add Dependencies

CSS DSL doesn’t need installation, but requires including the following artifacts in the build script:

  1. The ktor-html-builder artifact for HTML DSL:

CSS DSL - 图2

Gradle (Groovy)

Gradle (Kotlin)

Maven

CSS DSL - 图3

1. implementation "io.ktor:ktor-html-builder:$ktor_version"

  1. The kotlin-css-jvm artifact for building CSS:

CSS DSL - 图4

Gradle (Groovy)

Gradle (Kotlin)

Maven

CSS DSL - 图5

1. implementation "org.jetbrains:kotlin-css-jvm:$1.0.0-pre.129-kotlin-1.4.20"

Use CSS DSL

To send a CSS response, you need to extend ApplicationCall by adding the respondCss method to serialize a stylesheet into a string and send it to the client with the CSS content type:

1. suspend inline fun ApplicationCall.respondCss(builder: CSSBuilder.() -> Unit) {
2. this.respondText(CSSBuilder().apply(builder).toString(), ContentType.Text.CSS)
3. }

Then, you can provide CSS inside the required route:

1. get("/styles.css") {
2. call.respondCss {
3. body {
4. backgroundColor = Color.darkBlue
5. margin(0.px)
6. }
7. rule("h1.page-title") {
8. color = Color.white
9. }
10. }
11. }

Finally, you can use the specified CSS for an HTML document created with HTML DSL:

1. get("/html-dsl") {
2. call.respondHtml {
3. head {
4. link(rel = "stylesheet", href = "/styles.css", type = "text/css")
5. }
6. body {
7. h1(classes = "page-title") {
8. +"Hello from Ktor!"
9. }
10. }
11. }
12. }