Обрезать углы фигуры css

Блоки со срезанными углами в CSS

От автора: предположим, вы пытаетесь создать элемент дизайна в котором углы блока являются срезанными. Может быть, вы фанат «Звездного крейсера «Галактика»? Или, может быть, вам просто нравится этот необычный эффект, так как он отличается от стандартных прямоугольников.

Я подозреваю, что есть много способов сделать это. Конечно, вы можете использовать несколько фонов. Вы могли бы также использовать гибкую SVG-фигуру для фона элемента. Бьюсь об заклад, должен быть также какой-нибудь экзотический способ использовать градиенты, чтобы сделать это. Но есть и другие возможности создать с помощью CSS срезанные углы.

Мне нравится идея просто взять ножницы и обрезать нужные участки. По существу, именно это мы можем сделать с помощью clip-path. Мы можем использовать функцию polygon(), задать список координат X и Y и обрезать все, что находится за их пределами.

Посмотрите, что произойдет, если мы зададим три точки: среднюю верхнюю, нижнюю правую, нижнюю левую.

Онлайн курс по JavaScript

Научитесь создавать приложения со сложными интерфейсами

Это основной язык для современной веб-разработки — почти 100% сайтов работает на JavaScript. Освойте его с нуля всего за 4 месяца, и вы сможете зарабатывать от 70 000 рублей.

Источник

Tricks to Cut Corners Using CSS Mask and Clip-Path Properties

We recently covered creating fancy borders with CSS mask properties, and now we are going to cut the corners with CSS mask and clip-path ! A lot of techniques exist to cut different shapes from the corners of any element. In this article, we will consider modern techniques to create unique corner shapes while trying to work from reusable code that allows us to produce different results by adjusting variables. Check this online tool to get an idea of what we are building. It’s a CSS generator where you select the shape, the corners, and the size then you get the code in no time! As the diagram shows, the radial-gradient() creates the quarter of a circle and each conic-gradient() creates two perpendicular segments to cover two sides. It should be noted that overlapping gradients is not an issue since we are not going to change the CSS mask-composite property value. Using the same code an adjusting a few variables, we can get the shape for the other corners.

For the two-corner configuration we have two situations taking place. In the first situation, there are two opposite corners where we need two radial gradients and two conic gradients.

The configuration is almost the same as cutting only one corner: we add an extra gradient and update a few variables. In the second situation, there are two adjacent corners and, in this case, we need one radial gradient, one conic gradient, and one linear gradient.

“Wait!” you might exclaim. “How come the conic gradient covers three sides?” If you check the code, notice the repeat-y . In all of the examples, we always used no-repeat , but for this we can repeat one of them to cover more sides and reduce the number of gradients we use. Here is an example with only the conic-gradient() to understand the repetition. The trick is to have a height equal to 100% minus the border size so that the gradient fills that space when repeating, which covers the third side in the process.

You are probably wondering how one radial gradient is cutting two corners. To do this, we create half a circle that we place at the top left corner. Then by using a negative offset we cut two adjacent corners. Hover the below to understand the trick.

  1. We add a radial-gradient() on the corners we want to cut.
  2. We fill the sides using either a conic-gradient() or a linear-gradient() to create the final shape.

It should be noted that we can find different ways to create the same shape. What I am showing in this post are the methods I found to be best after trying lots of other ideas. You may have a different approach you consider to be better! If so, definitely share it in the comments!

Let’s tackle another type of cut shape: the angled cut.

We have two parameters: the size and angle of the cut. To get the shape, we need a conic-gradient() for each corner. This configuration is very similar to the example that kicked off this article.

Here is an illustration of one corner to understand the trick:

The difference between each corner is an extra offset of 90deg in from and the at position. The full code is like below:

--size: 30px; --angle: 130deg; --g: #0000 var(--angle), #000 0; mask: conic-gradient(from calc(var(--angle)/-2 - 45deg) at top var(--size) left var(--size),var(--g)) top left, conic-gradient(from calc(var(--angle)/-2 + 45deg) at top var(--size) right var(--size),var(--g)) top right, conic-gradient(from calc(var(--angle)/-2 - 135deg) at bottom var(--size) left var(--size),var(--g)) bottom left, conic-gradient(from calc(var(--angle)/-2 + 135deg) at bottom var(--size) right var(--size),var(--g)) bottom right; mask-size: 51% 51%; mask-repeat: no-repeat;

If we want to disable one corner, we remove the conic-gradient() for that corner and update the size of another one to fill the remaining space exactly like we did with the circular cut. Here’s how that looks for one corner:

We can do the exact same thing for all the other corners to get the same effect.

In addition to CSS mask, we can also use the CSS clip-path property to cut the corners. Each corner can be defined with three points.

Zooming in on a corner of the shape showing the three points that form the angled cut.

The other corners will have the same value with an offset of 100% . This gives us the final code with a total of 12 points — three per corner.

/* I will define T = [1-tan((angle-90)/2)]*size */ clip-path: polygon( /* Top-left corner */ 0 T, size size,0 T, /* OR 0 0 */ /* Top-right corner */ calc(100% - T) 0,calc(100% - size) size,100% T, /* OR 100% 0 */ /* Bottom-right corner*/ 100% calc(100% - T),calc(100% - size) calc(100% - size), calc(100% - T) 100%, /* OR 100% 100% */ /* Bottom-left corner */ T 100%, size calc(100% - size),0 calc(100% - T) /* OR 0 100% */ )

Notice the OR comments in that code. It defines the code we have to consider if we want to disable a particular corner. To cut a corner, we use three points. To uncut a corner, we use one point — which is nothing but the coordinate of that corner.

When the angle is equal to 90deg , we can optimize the code of the gradient version and rely on fewer gradients. To cut four corners we can use only one gradient:

--size: 30px; mask: conic-gradient(at var(--size) var(--size),#000 75%,#0000 0) 0 0/calc(100% - var(--size)) calc(100% - var(--size))

This doesn’t remind you of something? It’s exactly similar to the circular cut-out! For the 90deg we have two gradient methods, the first one we detailed previously where each corner is cut with one gradient, and this last method where we cut all the corners using one gradient. I think you know the rest of the story: to uncut some corners we combine the last method with a conic gradient

Two methods with gradients, one with clip-path, we have to add a conic-gradient?! I am lost …

As I said, no need to remember all the methods and tricks. The generator will do the job of generating the code for you. I simply try to make this article as detailed as possible to cover all the possible cases.

Oof, we have reached the last and trickiest shape at last! This one can be achieved with either gradients or clip-path , but let’s go with the clip-path approach.

Things would get complex and verbose if we go with the gradient approach. Here’s a demo that illustrates that point:

There are nine gradients total, and I am still not done with the calculation. As you can tell, the thickness of the border is incorrect, plus the final result is unsatisfying due to the nature of gradients and their anti-aliasing issues. This approach might be a good exercise to push the limit of gradients, but I don’t recommend it in a production environment.

So, back to the clip-path method. We will still wind up with verbose code, but less of a big deal since the generator can do the job for us with a cleaner end result.

Here is an overview of the path. I am adding a small gap to better see the different points but we should have an overlap of points instead.

The way we calculate the outer points is the same as how we did it for the regular angled cut. For the inner points, however, we need more math. Don’t worry, I’ll spare you some “boring” geometry explanation for this one. I know most of you don’t want it, but in case you need to dig into this, you can check the JavaScript file of the generator to find the code and the math I am using to generate the shape.

There’s a special case for the angle cut I want to call out. It’s where we use an angle equal to 180deg . Here’s what that produces:

We have a straight line on the corner so we can optimize the clip-path code. For the full shape, we can use eight points (two points per corner) instead of 12. And for the border-only version, we can use 18 points (nine inner points and outer points) instead of 26. In other words, we can remove the middle point.

The border-only shape can also be made using gradients. But rather than using nine gradients like we did before, we can get away with only four linear gradients and a clean result.

We just combined CSS masks with gradients to create some fancy shapes without resorting to hacks and a lot of code! We also experienced just how much it takes to strike the right balance of code to get the right results. We even learned a few tricks along the way, like changing values by one or even half a unit. CSS is super powerful!

But, as we discussed, the online generator I made is a great place to get the code you need rather than writing it out by hand. I mean, I went through all the work of figuring out how all of this works and I would likely still need to reference this very article to remember how it’s all put together. If you can memorize all of this, kudos! But it’s nice to have a generator to fall back on.

Источник

Читайте также:  php-generated 503
Оцените статью