CartoCSS basics in CARTO Editor
In this lesson, we will give you a five minute overview of CartoCSS basics, which you can use to style your maps.
Our goal with this lesson: Use CartoCSS to create custom styles for map polygons based on dataset categories.
By the end of this lesson, you will be able to make this map:
Cascading Style Sheets for Maps
CartoCSS is very similar in structure to Cascading Style Sheet code, or CSS. The code contains a selector that specifies the HTML element you’re applying style to, a property of that element that you’re going to change the style of, and a value that defines what you want the property to look like.
CartoCSS allows you to control styles specifically for map elements. Selectors are typically the name of the dataset you are visualizing on a map, but they can also be other elements:
In this lesson we’re targeting a map layer created from our “Null Island Election Districts” dataset, so our selector is
Where does CartoCSS code go?
In our CARTO interface, you can click on the CSS menu button and write code into the CartoCSS editor panel. If you’re using HTML and CARTO.js to build your map, you can also write CartoCSS into your code using these methods.
CartoCSS Properties and Values
CARTO’s default CartoCSS
When you import a dataset into your CARTO account and check it’s Map View, you will see styling already applied to your data. CARTO’s default CartoCSS defines color, opacity, and line-width for polygons, point markers, and/or lines. It’s values include color defined with hexadecimal code, opacity values ranging from 0 (fully transparent) to 1 (fully opaque), and line width for stroke measured in pixels.
Other CartoCSS properties
A list of CartoCSS properties can be found here, including
line-dasharray. The first number value for the
line-dasharray property is dash width. The second is the width of the space between dashes. You can use more than one pair of dash width and space width numbers.
Styling a map by category
You can have your CartoCSS style rules apply to only a subset of your data. To do that use brackets containing a column name from your dataset, and only the column value you would like the style to apply to.
We also used the CartoCSS below for labels.
Using images with CartoCSS
Another CartoCSS property example is polygon-pattern-file. This property takes an image url for its value, because it is used to fill your polygon with a tiled picture. You can change the image fill opacity using the polygon-pattern-opacity property. If less than maximum opacity is used in addition to a polygon-fill color, the color will show up beneath the image fill layer.