Волнистая граница блока css

Разделительная линия в виде волны на css

Продолжаем творить трюки на чистом css. Сегодня я расскажу, как на средствами css сделать красивую разделительную линию в виде волны на сайте. Ее можно использовать, например, для визуального разделения постов на блоге, или отдельных блоков в сайдбаре.

Когда-то я уже рассказывал о стильной разделительной линии на css. Но там применялся тег-динозавр hr с парочкой хитрых правил в стилях, позволявших поиграться с тенью.

Сегодня же совсем иной расклад. Для отображения линии в виде волны придется добавить в правила гораздо больше хитростей и применять уже не просто css, а css3. Вэлкам!

Для начала обычный html код. Линии мы будем выводить пустыми блоками div со специальными наборами правил. Пустые блоки — это, конечно же, зло. Но иногда приходится с ним мириться.

Здесь мы показали 4 вида линий. А вот так будет выглядеть набор стилей в css для них:

.wave overflow: hidden;
position: relative;
width: 630px;
height: 50px;
>
.line position: absolute;
width: 630px;
height: 26px;
>
.line1 background: linear-gradient(45deg, transparent, transparent 49%, black 49%, transparent 51%);
>
.line2 background: linear-gradient(-45deg, transparent, transparent 49%, black 49%, transparent 51%);
>
.line background-size: 50px 50px;
>
.smallLine position: absolute;
width: 630px;
height: 5px;
>
.smallLine1 background: linear-gradient(45deg, transparent, transparent 49%, black 49%, transparent 51%);
>
.smallLine2 background: linear-gradient(-45deg, transparent, transparent 49%, black 49%, transparent 51%);
>
.smallLine background-size: 10px 10px;
>
.circle position: absolute;
width: 630px;
height: 20px;
background: radial-gradient(16px, transparent, transparent 4px, black 4px, black 10px, transparent 11px);
background-size: 30px 40px;
>
.circle2 top: 20px;
left: 15px;
background-position: 0px -20px;
>
.ellipse position: absolute;
background: radial-gradient(ellipse, transparent, transparent 7px, black 7px, black 10px, transparent 11px);
background-size: 36px 40px;
width: 630px;
height: 20px;
>
.ellipse2 top: 20px;
left: 18px;
background-position: 0px -20px;
>

Читайте также:  Функция dict python 3

Здесь мы использовали такие фишки как linear-gradient и radial-gradient из арсенала css3.
Есть и другой вариант применения разделительной линии в виде волны (самая нижняя на иллюстрации в начале поста). Ее можно применять в конце какого-либо блока, как нижнее оформление. Код достаточно прост. Сначала html:

В правилах css применим псевдоэлементы :before и :after. О них вы можете прочитать здесь. Вот как будет выглядеть код:

.wave width: 630px;
background: #333;
height: 30px;
position: relative;
>
.wave::before content: «»;
position: absolute;
left: 0;
bottom: 0;
right: 0;
background-repeat: repeat;
height: 10px;
background-size: 20px 20px;
background-image:
radial-gradient(circle at 10px -5px, transparent 12px, #19d1ff 13px);
>
.wave::after content: «»;
position: absolute;
left: 0;
bottom: 0;
right: 0;
background-repeat: repeat;
height: 15px;
background-size: 40px 20px;
background-image:
radial-gradient(circle at 10px 15px, #19d1ff 12px, transparent 13px);
>

Источник

How to Create Wavy Shapes & Patterns in CSS

The wave is probably one of the most difficult shapes to make in CSS. We always try to approximate it with properties like border-radius and lots of magic numbers until we get something that feels kinda close. And that’s before we even get into wavy patterns, which are more difficult. “SVG it!” you might say, and you are probably right that it’s a better way to go. But we will see that CSS can make nice waves and the code for it doesn’t have to be all crazy. And guess what? I have an online generator to make it even more trivial! Two gray circles.We have two circles with the same radius next to each other. Do you see that red line? It covers the top half of the first circle and the bottom half of the second one. Now imagine you take that line and repeat it. A squiggly red line in the shape of waves.We already see the wave. Now let’s fill the bottom part (or the top one) to get the following: Red wave pattern.Tada! We have a wavy shape, and one that we can control using one variable for the circle radii. This is one of the easiest waves we can make and it’s the one I showed off in this previous article Let’s add a bit of complexity by taking the first illustration and moving the circles a little: Two gray circles with two bisecting dashed lines indicating spacing.We still have two circles with the same radii but they are no longer horizontally aligned. In this case, the red line no longer covers half the area of each circle, but a smaller area instead. This area is limited by the dashed red line. That line crosses the point where both circles meet. Now take that line and repeat it and you get another wave, a smoother one. A red squiggly line. A red wave pattern.I think you get the idea. By controlling the position and size of the circles, we can create any wave we want. We can even create variables for them, which I will call P and S , respectively. You have probably noticed that, in the online generator, we control the wave using two inputs. They map to the above variables. S is the “Size of the wave” and P is the “curvature of the wave”. I am defining P as P = m*S where m is the variable you adjust when updating the curvature of the wave. This allows us to always have the same curvature, even if we update S. m can be any value between 0 and 2 . 0 will give us the first particular case where both circles are aligned horizontally. 2 is a kind of maximum value. We can go bigger, but after a few tests I found that anything above 2 produces bad, flat shapes. Let’s not forget the radius of our circle! That can also be defined using S and P like this:

When P is equal to 0 , we will have R = S/2 . We have everything to start converting all of this into gradients in CSS!

Our waves use circles, and when talking about circles we talk about radial gradients. And since two circles define our wave, we will logically be using two radial gradients. We will start with the particular case where P is equal to 0 . Here is the illustration of the first gradient:

This gradient creates the first curvature while filling in the entire bottom area —the “water” of the wave so to speak.

The —size variable defines the radius and the size of the radial gradient. If we compare it with the S variable, then it’s equal to S/2 . Now let’s add the second gradient:

radial-gradient(var(--size) at 50% var(--size), blue 99%, #0000 101%) calc(50% - 2*var(--size)) 0/calc(4 * var(--size)) 100%

That’s because we can reach the same result using different gradient configurations. You will notice a slight difference in the alignment if you compare both configurations, but the trick is the same. This can be confusing if you are unfamiliar with gradients, but don’t worry. With some practice, you get used to them and you will find by yourself that different syntax can lead to the same result. Here is the full code for our first wave:

Now let’s take this code and adjust it to where we introduce a variable that makes this fully reusable for creating any wave we want. As we saw in the previous section, the main trick is to move the circles so they are no more aligned so let’s update the position of each one. We will move the first one up and the second down. Our code will look like this:

I have introduced a new —p variable that’s used it to define the center position of each circle. The first gradient is using 50% calc(-1*var(—p)) , so its center moves up while the second one is using calc(var(—size) + var(—p)) to move it down. A demo is worth a thousand words:

The circles are neither aligned nor touch one another. We spaced them far apart without changing their radii, so we lost our wave. But we can fix things up by using the same math we used earlier to calculate the new radius. Remember that R = sqrt(P² + S²)/2 . In our case, —size is equal to S/2 ; the same for —p which is also equal to P/2 since we are moving both circles. So, the distance between their center points is double the value of —p for this:

R = sqrt(var(--size) * var(--size) + var(--p) * var(--p))

This is valid CSS code. sqrt() is part of the specification, but at the time I’m writing this, there is no browser support for it. That means we need a sprinkle of JavaScript or Sass to calculate that value until we get broader sqrt() support. This is pretty darn cool: all it takes is two gradients to get a cool wave that you can apply to any element using the mask property. No more trial and error — all you need is to update two variables and you’re good to go!

What if we want the waves going the other direction, where we’re filling in the “sky” instead of the “water”. Believe it or not, all we have to do is to update two values:

We’re using the left and bottom keywords to specify the sides and the offset. By default, the browser defaults to left and top — that’s why we use 100% to move the element to the bottom. In reality, we are moving it from the top by 100% , so it’s really the same as saying bottom . Much easier to read than math! With this updated syntax, all we have to do is to swap bottom for top — or vice versa — to change the direction of the wave.

And if you want to get both top and bottom waves, we combine all the gradients in a single declaration:

If you check the code, you will see that in addition to combining all the gradients, I have also reduced their height from 100% to 51% so that they both cover half of the element. Yes, 51% . We need that little extra percent for a small overlap that avoid gaps.

It’s your homework! Take what we did with the top and bottom sides and try to update the values to get the right and left values. Don’t worry, it’s easy and the only thing you need to do is to swap values. If you have trouble, you can always use the online generator to check the code and visualize the result.

Earlier, we made our first wave using a red line then filled the bottom portion of the element. How about that wavy line? That’s a wave too! Even better is if we can control its thickness with a variable so we can reuse it. Let’s do it! For the other cases, it’s the issue related to some rounding that will results in misalignment and gaps between the waves: That said, I still think the method we covered remains a good one because it produces smooth waves in most cases, and we can easily avoid the bad results by playing with different values until we get it perfect.

I hope that after this article, you will no more to fumble around with trial and error to build a wavy shape or pattern. In addition to the online generator, you have all the math secrets behind creating any kind of wave you want! The article ends here but now you have a powerful tool to create fancy designs that use wavy shapes. Here’s inspiration to get you started…

What about you? Use my online generator (or write the code manually if you already learned all the math by heart) and show me your creations! Let’s have a good collection in the comment section.

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Источник

Кто знает как сделать границы DIV в виде волн?

Всем привет!
Нужно сделать границы DIV в виде волн но разных разверов. Есть у кого то какие то идеи/предложения/опыт подобного?

5af4bf06bb9ed887085266.png

Пробовал как фон, но как на меня решение топорное — може есть что то лучше .
Буду рад любым(по вопросу) советам !))
ПС — картинка как оно должно быть

profesor08

Сделай волну на svg. Просто посмотри что из себя представляет svg path. Твоя задача сгенерировать аналогичный твоему в макете.

Вот пример (В поле для скриптов увидишь кнопку настроек, там список подключенных библиотек, если понадобятся.)
https://codepen.io/peacepostman/pen/jBavvN?editors=0110

Но лично я бы сделал на canvas, так проще и результатом проще управлять.
https://codepen.io/Profesor08/pen/ddGoxa

Первый пример Вот вообще то что доктор прописал — но мне нужно без анимации .
Относительно canvas — даже не думал.

lukoie

Раз надо разные волны, нужны две дивки, у одной волна вверху, у второй -внизу, и делать их разными. А вместе они сходятся по прямой линии
Вот волна: https://jsfiddle.net/b2oytyL2/
или вот я Вам такую хрень забабацал: https://jsfiddle.net/cjw2qo9e/

Вам наверное проще всего будет в иллюстраторе сделать форму, и экспортнуть ее в свг

Да я тоже пробовал все делать на свг но оно должно быть и адаптивним + в качестве фона там градиент и высота блока может менятся. Сейчас сделал несколько блоков с :before/after куда вставил картинки с фоном волны. но есть один блок на котором я остановился

5af5b062c5009190580370.png

lukoie

lukoie

lukoie, блин ну вот просто выручил!!
И еще один вопрос, а можно как то сделать высоту свг адаптивной(в зависимости от высоты родителя)?

Источник

Оцените статью