border
Свойство border отвечает за отрисовку видимой границы блока. Часто видимую границу блока называют рамкой.
Само свойство border является шорткатом (короткой записью) и объединяет в себе значение для нескольких полных свойств:
Пример
Скопировать ссылку «Пример» Скопировано
Украсим текстовую карточку цветной сплошной рамкой.
Повседневная практика показывает, .
div class="element"> p>Повседневная практика показывает, . p> div>
Зададим рамку толщиной 5 пикселей, сплошную, цвета #ED6742:
.element border: 5px solid #ed6742;>
.element border: 5px solid #ed6742; >
🛠 Ещё немного про треугольники. А точнее, стрелки. Их тоже можно создать при помощи border , но тут понадобится подключить свойство transform , чтобы повернуть элемент с рамками на 45 градусов в нужную сторону:
div class="arrows"> div class="arrow _prev">div> div class="arrow _next">div> div>
.arrows max-width: 1200px; height: 250px; margin: 0 auto; background-color: #f1f1f1;> .arrow /* Рисуем квадрат */ width: 50px; height: 50px; /* Задаём левую рамку */ border-left: 5px solid #ff0001; /* Задаём нижнюю рамку */ border-bottom: 5px solid #ff0001;> .arrow._prev /* Поворачиваем квадрат нижним левым углом влево */ transform: rotate(45deg);> .arrow._next /* Поворачиваем квадрат нижним левым углом вправо */ transform: rotate( -135deg );>
.arrows max-width: 1200px; height: 250px; margin: 0 auto; background-color: #f1f1f1; > .arrow /* Рисуем квадрат */ width: 50px; height: 50px; /* Задаём левую рамку */ border-left: 5px solid #ff0001; /* Задаём нижнюю рамку */ border-bottom: 5px solid #ff0001; > .arrow._prev /* Поворачиваем квадрат нижним левым углом влево */ transform: rotate(45deg); > .arrow._next /* Поворачиваем квадрат нижним левым углом вправо */ transform: rotate( -135deg ); >
Чем не стрелки для слайдера? 🤗
🛠 Часто встречающийся дизайнерский приём — появление рамки вокруг элемента при наведении на него курсора мыши.
Если просто добавлять рамку по селектору :hover , то элемент будет дёргаться. Причина в том, что размер элемента увеличивается на ширину рамки. Чтобы подобных подёргиваний не происходило, изначально задайте рамку нужной толщины, но установите ей прозрачный цвет ( transparent ). А по наведению курсора просто меняйте цвет на нужный. Profit! Вы прекрасны 😄
Create Multi-colored Borders using CSS
The CSS border property does have some customization options, such as choices like solid, dashed, dotted, etc. However, when it comes to border color, we can only have a solid color per side. But, there is another way to achieve a multi-colored line using a few more properties you might not have thought of, let’s take a look.
Solid
Dashed
Dotted
Multi-colored Borders
To achieve a multi-color border like shown above, we will use the position property and the ::after selector with a color gradient. First, we will make a header area using a HTML class and then we will style it with CSS to have a multi-color border dividing it and the content below.
Now, let’s style it a bit with CSS.
h1 font-size: 50px;
line-height: 100px;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
>
.ost-multi-header position: relative;
height: 100px;
background: #999999;
>
You should now have something that looks like this:
With that, we can now add ::after to the .ost-multi-header selector . But, before we do, I’d like to explain a little of what ::after is doing and why we need the position property for the multi-color border. The ::after creates a pseudo-element with whatever is in the content property at the end of the selected element. In our case, that element is .ost-multi-header . Let us make a time-honored “Hello World!” example to illustrate.
.ost-multi-header::after content: 'Hello World!';
position: absolute;
left: 20px;
bottom: 0;
>
As you can see, we now have a “Hello World!” element below the header title. Because our parent element, .ost-multi-header , has the position property as relative , we can give a child element an absolute position. This will let us move our new pseudo-element we created with ::after wherever we like within the parent element easily. We put it at the bottom and move it over 20px from the left within the parent element. Note, if the parent element didn’t have position property set to relative, then our absolute positioned element would be at the bottom and 20px to the left of the browser’s viewport.
What about our colored border? We are going to style the background of our pseudo-element to be our multi-colored border using a gradient. CSS gradients can be linear or radial. For our border, we will use linear-gradient . Quite simply, this would give us the border we seek.
.ost-multi-header::after content: '';
height: 6px;
position: absolute;
left: 0;
right:0;
bottom: 0;
background: linear-gradient(to right, #ed8034 0%,#ed8034 33%,#feb123 33%,#feb123 66%,#2184cd 66%,#2184cd 100%);
>
But, let’s slow down a moment for a step-by-step. First, the content property is still there even though it is blank. This is because, without the content property, the pseudo-element is never created; so, we need it. We need to set the height of our pseudo-element, our border height. Why set both left and right properties to 0? Without a set width, this will stretch the pseudo-element to be 100% width inside the parent element. It may look like a lot, but the linear-gradient settings are just telling the color to flow from left “to right”, and we put in what colors we want at certain percentages of the background.
Even though all we are doing is picking what colors to be at specific percentages, it is a lot of leg work. Luckily, there are free online resources that help tremendously with color gradients. Ultimate CSS Gradient Generator by ColorZilla is a great tool that includes multiple gradient properties for supporting older browsers.
We have an already setup gradient on the tool, so we can use this link to see the exact settings used in this tutorial: https://colorzilla.com/gradient-editor/#ed8034+0,ed8034+33,feb123+33,feb123+66,2184cd+66,2184cd+100. It should look like this:
There are a lot of settings on this site, but let us focus on what settings we needed to create the look we are going to use for our border. Let’s break it down:
- Presets – These can be a great starting point!
- Slider bar – You can add, remove, and edit colors here
- Stops – This section allows you to change the settings for each color’s opacity and location. Simply click the color box on the slider above to change which one you are controlling in this section.
- Preview – Here you can immediately see the results of your changes.
- Orientation & Size – This allows you to change from horizontal, vertical, diagonal, or radial. And to set the size of the gradient.
- CSS Code – The generated code with a permalink so you can always go back and edit your gradient easily.
We weren’t looking for a faded gradient in our case, but rather a solid flat transition between two colors, so all we have to do is stack the two colors on top of eachother where we want this to happen. In our example, we stacked colors at 33% and 66% respectively.
Feel free to play around with the settings, knowing that what you see in the preview is what the code will generate. When you get the look setup the way you want, you can use the “copy” button in the lower right hand of the code box.
If you copied the code as I had it in the link, your final CSS will look something like this:
h1 font-size: 50px;
line-height: 100px;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
>
.ost-multi-header position: relative;
height: 100px;
background: #999999;
padding-bottom: 6px;
>
.ost-multi-header::after content: '';
height: 6px;
position: absolute;
left: 0;
right: 0;
bottom: 0;
/* Permalink - use to edit and share this gradient: https://colorzilla.com/gradient-editor/#ed8034+0,ed8034+33,feb123+33,feb123+66,2184cd+66,2184cd+100 */
background: rgb(237,128,52); /* Old browsers */
background: -moz-linear-gradient(left, rgba(237,128,52,1) 0%, rgba(237,128,52,1) 33%, rgba(254,177,35,1) 33%, rgba(254,177,35,1) 66%, rgba(33,132,205,1) 66%, rgba(33,132,205,1) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(left, rgba(237,128,52,1) 0%,rgba(237,128,52,1) 33%,rgba(254,177,35,1) 33%,rgba(254,177,35,1) 66%,rgba(33,132,205,1) 66%,rgba(33,132,205,1) 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to right, rgba(237,128,52,1) 0%,rgba(237,128,52,1) 33%,rgba(254,177,35,1) 33%,rgba(254,177,35,1) 66%,rgba(33,132,205,1) 66%,rgba(33,132,205,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ed8034', endColorstr='#2184cd',GradientType=1 ); /* IE6-9 */
>
And, that CSS will produce this multi-colored underline that is fully responsive:
There we go! We didn’t have to add the 6px padding to the bottom of .ost-multi-header , but the absolute positioned child doesn’t affect the height of the parent element anymore. We can let it float on top of our content in the parent element, or add padding to ensure it doesn’t cover any content we might not want obstructed.
Here is a link to this exercise recreated on CodePen for everyone to edit and learn without worry.
One final note, some older browsers only support the single colon :after selector, and not the modern standard double ::after . You can use the single colon if you wish to be safe. It will also work in modern browsers for now.
How to make a CSS border with two different colors
Here is a quick way to make an HTML element have two different border colors.
Instead of using some kind of weird div overlay with hacky positioning, instead of using a background image, we have a very straightforward method to produce a standards compliant border with two unique colors!
Take a look:
[css]
outline:1px solid #f00;
border:1px solid #333;
[/css]
Just copy->paste that into your CSS class or id and use it right away!
Example
Here is a sample usage of the above idea, we have a div with two borders with different colors, some padding, and a centered margin (using auto).
We created a class named doubleColor that will hold all of the styling for our element with two different colored borders.
[css].doubleColor width:150px;
height:100px;
padding:10px;
outline:3px solid #f00;
border:3px solid #333;
margin: 0 auto 10px;
>
[/css]
And the html:
[html]
Let’s try it out – this box below will have two borders with different colors:
Please note: When viewed in IE7, this reverts to just the single border appearance using the rules of the “border” CSS property, but this will function correctly in IE8+.
There you have it! A CSS trick that let’s you use more than one color as a border for an element. That was easy!
Example 2 – border with two colors and rounded corners
Here is a different method that you can use to create a CSS border with two colors and rounded corners.
We created a class named outerColor that will hold all of the styling for the outer element color. Notice the background color for this element (#333) matches the border color of the inner content.
[css].outerColor width:150px;
height:100px;
border-radius:10px;
border:3px solid #f00;
margin: 0 auto 10px;
background:#333;
>
[/css]
We then created a class named innerColor that will hold all of the styling for the inner element color. Notice the modifications to the height and width to take into account padding and border size. Also notice the background color is white for the inner content.
[css].innerColor width:124px;
height:74px;
border-radius:10px;
border:3px solid #333;
background:#fff;
padding:10px;
>
[/css]
And the html:
[html]
Let’s try it out – this box below will have two borders with different colors and rounded corners (if your browser supports CSS3 that is!):
So now you can make a CSS border with two colors and rounded corners using border-radius. Pretty cool huh?