How can I create a polka dot border?

不打扰是莪最后的温柔 提交于 2019-12-12 13:09:21

问题


I am trying to create a polka dot border around my content. For example:

I have managed to achieve this by repeating an image (of two individual dots).

.dots {
    background: url('/images/dots.png'), url('/images/dots.png'), url('/images/dots.png'), url('/images/dots.png');
    background-repeat: repeat-y, repeat-y, repeat-x, repeat-x;
    background-position: right top, left top, right top, right bottom;
}

However it is an imperfect result. On certain sizes the dots will start to overlap.

I'm not sure how to avoid this problem as the image doesn't seamlessly tile.

Is there some other approach I could take for an effect which doesn't suffer from these faults?


回答1:


You can easily do this with radial-gradient as a repeated background then adjust the values depending on the height/width of the container:

.dots {
  width:300px;
  height:200px;
  padding:60px 70px;
  box-sizing:border-box;
  background:
  linear-gradient(#fff,#fff) 68px 50px/calc(100% - 136px) calc(100% - 100px) no-repeat,
  radial-gradient(circle at 12px 12px,#000 20%, transparent 22%) 12px 2px/33px 50px,
  radial-gradient(circle at 12px 12px,#000 20%, transparent 22%) 33px 27px/33px 50px;
}
<div class="dots">
  The content here
</div>



回答2:


The problem is occurring because your background image is not as wide as the screen, and is trying to repeat itself.

To correct this, the easiest solution would be background-size: cover. This ensures that the image fills the entire screen, meaning it will never 'wrap around'. Note that this will stretch the image so that some distortion occurs depending on the aspect ratio.

If distortion is a concern, there are other two possible solutions:

  1. Ensure that the image is as large as the largest screen resolution you want to display it on (optimally additionally scaling up the size of the displayed image based on viewport)
  2. Craft the image so that it perfectly overlaps itself when it wraps around, and then make use of background-repeat.

Here's an example of background-size: cover:

.dots {
  border: 5px solid black; /* For Snippet */
  height: 50vh; /* For Snippet */
  width: 50vw; /* For Snippet */
  background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/Polka_dots.svg/1200px-Polka_dots.svg.png');
  background-size: cover;
}
<div class="dots"></div>


来源:https://stackoverflow.com/questions/48980036/how-can-i-create-a-polka-dot-border

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!