Creating a Dotted Line in CSS
How to create a dotted line that appears the same in most browsers.
By. Jacob
Edited: 2020-03-14 13:24
It is possible to create a dotted line with pure CSS using repeating-linear-gradient, which can work as a useful replacement of- or custom styling of the hr element.
The trick works by using rgba to apply a transparent background for every other pixel. To make this work on a hr or div element we need only to apply a few other properties. It can also be useful to use :after to create a pseudo-element in the HTML.
The CSS for this trick:
hr {border:none;}
hr:after {
height: 1px;
display: block;
content: " ";
background: repeating-linear-gradient(to right, rgba(0,0,0,0.5) 0,
rgba(0,0,0,0.5) 1px, rgba(255,255,255,0) 1px,
rgba(255,255,255,0) 2px);
}
The above will also work with a div element, just shift out "hr" with "div".
Note. Since the hr elements "line" is created by a border, we use border:none; to remove the default styling.
Dotted line with a CSS gradient
The repeating-linear-gradient CSS function opens up for many possibilities. In this case, we just want to make a "gradient" that is repeating horizontally. We are not really making a gradient though! We will be making a dotted line instead of a gradient.
Creating a dotted line in this way could be better than relying on a CSS border, since it might appear different depending on browser and device in use.
div:after {
background: repeating-linear-gradient(to right, rgba(0,0,0,0.5) 0,
rgba(0,0,0,0.5) 1px, rgba(255,255,255,0) 1px,
rgba(255,255,255,0) 2px);
}
The first color-stop is black, starts at 0px and ends at 1px, and the second range is white, starts at 1px, and ends at 2px.
Since the repeating-linear-gradient function will keep repeating the colors we choose, the box will automatically be filled out in all directions.
Using a CSS border
It is also possible to make a dotted line using the CSS border-bottom property, and in many cases this should actually be sufficient to fulfill our design goals. It may not appear exactly the same in all browsers, but that is rarely a big issue.
See also: Should a Website Look The Same in All Browsers?
To instead use the border-bottom property, you can do like this:
div {
border-bottom: 1px dotted #000;
height:1px;
}
You do not need to apply a width on block elements, as they will automatically take up 100% of the parents width.
Tell us what you think: