-->

Create a perfect dashed line with background-image

2020-07-18 11:08发布

问题:

I would like to have a dotted line below to a text :

The web designer have designed a custom dotted so i can’t use :

h2 {
    border-bottom: 4px dashed #fff;
    display:table;
} 

because it is not conform.

What i’ve done : I’ve made an image with a dot and position it with css :

h2 {
    padding-bottom: 20px;
    display:table;
    background-image: url('../images/tiret.png');
    background-repeat: repeat-x;
    background-position: center bottom; 
}

It works very well but depending on the width of the text, the last dot could appear cut like you can see on this picture :

Do you have a suggestion on how to avoid this ?

回答1:

You can use border-image:

h1 {
  display: inline-block;
 border-style: solid;
border-width: 0px 0px 12px;
-moz-border-image: url(http://yurigor.com/wp-content/images/goldstar.png) 0 0 286 round;
-webkit-border-image: url(http://yurigor.com/wp-content/images/goldstar.png) 0 0 286 round;
-o-border-image: url(http://yurigor.com/wp-content/images/goldstar.png) 0 0 286 round;
border-image: url(http://yurigor.com/wp-content/images/goldstar.png) 0 0 286 round;
}
<h1>Hello world</h1>

Codepen here

Also there is usefull online generator



回答2:

You could try background-repeat:space

The image is repeated as much as possible without clipping. The first and last images are pinned to either side of the element, and whitespace is distributed evenly between the images. The background-position property is ignored unless only one image can be displayed without clipping. The only case where clipping happens using space is when there isn't enough room to display one image.