Document

How to Add Border Gradient in CSS [+3 Tools]

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

The border property in CSS allows web designers to specify the style, width, and color of the borders of an element.

In CSS, a gradient allows a designer to apply a smooth transition between two or more colors. You can use gradients to create visual effects such as shading, color blending, and texture on the elements on your web page.

Border gradient is a CSS property that allows developers to apply a gradient to an element’s border.

A gradient border creates a visual effect where the border’s color changes from one color to another.

Why use a gradient border?

Border gradients were among the various styling features that were introduced in CSS3. These are some of the reasons why you should have it on your next web app:

  • A border gradient is flexible: You can create complex and layered effects using gradient borders. This is unlike solid color borders, which are rigid. Gradient borders are thus useful when dealing with complex layouts or shapes that demand nuanced visual designs.
  • Create visual appeal: Using the gradient border effect, you can add eye-catching visual effects to your designs. For instance, you can use bold color contrasts to help draw attention to a specific element on your webpage.
  • Provide seamless integration: Gradient borders allow you to seamlessly integrate the border into your element’s background. Such an approach gives your webpage a solid and cohesive look, showing a well-thought design.

How to add Border Gradient in CSS

Before we demonstrate how to add a border gradient , we can illustrate how to add a border to an HTML element.

          
How to add a Border illustrated.

The rendered page will appear as:

Border-Illustrated

Even though the above code has a border, it is not so appealing to the eyes as it is blank. We only have a 5px solid Rebecca purple border around our div.

We can make our border appealing using border gradients. There exist different approaches to adding a border gradient. The following are some of the major ones:

Using Gradient Borders (Linear Gradient, Radial Gradient, Conic Gradient)

We will illustrate how to use Gradient Borders in three different ways:

Linear Gradient

A linear gradient creates a smooth transition between two or more colors in a straight line. We can use the following code to demonstrate:

      
Linear Gradient Illustration

We have specified the border style as solid, meaning the border around our box is a solid line. The border width on our code is 10px.

Читайте также:  Copy files using php script

The linear gradient starts with rgb(143, 55, 0)” and ends with “rgb(66, 228, 250)”. We have also specified a 45 degrees angle. The width of the border image slice is set to “1”.

The rendered page will appear as:

Linear

Radial Gradient

A radial gradient creates a circular gradient radiating from a central point, allowing users to transition from one color to another in a web page’s element.

We can illustrate how to add a radial gradient using this code:

      
Radial Gradient Illustration

We have set the border style of our element as solid. We have also given our border a border width of 5px.

The radial gradient starts with dark green RGB(0,143,104) and ends with bright yellow, denoted by rgb(250,224,66).

The ‘1’ at the end of the code represents the border-image-repeat property. This value instructs the browser to repeat the border image only once around the element’s border.

The rendered page will appear as:

Radial-Gradient

Conic Gradient

A conic gradient creates a circular color transition. In this effect, the transition starts from a central point and then spreads outwards, forming a circular effect.

      
Conic Gradient Illustration

In this code, we set the border style as solid and give the border a width of 7.5px. The border-image property sets the border gradient. There are seven colors, starting with red and ending with rgb(255, 0, 38).

Figure ‘1’ at the end of the code gives the border width of 1 pixel.

The rendered page will appear as:

Conic-gradient

Using Border Images

Border images replace the standard solid borders of HTML elements. Border images are used to create complex designs instead of combining colors to create a border gradient.

      
Border Images Illustration

We have given our border-width property a width of 15px and set the border-style as solid.

The border-image-slice sets the width and height of the border box to 60% and 30%, respectively.

The rendered page will appear as:

Border-Images

Using Shorthand Property

A shorthand property allows developers to style multiple individual CSS properties using one line of code. For this case, we use border-image to specify border-image-source and border-image-slice.

      
Shorthand Property Illustration

The rendered page will appear as:

Shorthand

CSS border gradient generators

CSS border gradient generators help developers add gradient effects on elements on a web page. These generators allow you to adjust the settings, meaning you don’t have to create everything from scratch. The following are some of the tools you can use:

#1. CSS Gradient Generator-Converting Colors

The Converting Colors allows you to generate linear or radial gradient CSS code with up to five colors. The CSS gradient code you generated can be used as an element’s border or background image.

Converting-Colors

You can do the following with this generator;

  • Select up to five colors and use them in the border gradient.
  • Choose the direction of the gradient. The tool has both linear and radial gradients.
  • You can decide how the transition of colors happens using the color stop feature.
Читайте также:  Php позиция последнего вхождения символа

Once you are done experimenting and generating the code, you can copy and use it on your website.

#2. CSS Border Gradient Generator-Unused CSS

Unused-CSS helps developers generate gradient borders that they can apply to block elements without creating pseudo-elements or extra elements.

UnusedCSS

  • Choose between different gradient types. You can easily switch between radial and linear gradients when working with this tool.
  • Preview tab. The tool lets you preview how the border gradient will appear on your web page as you customize it.
  • Color stops. This tool makes it easy to decide how transitions will occur for different colors.
  • Border size customization. You can customize the border size and border radius easily with this tool.

Once you are satisfied with the code generated, you can copy and use it on your project.

#3. Gradient Border Generator- Amit Sheen

This tool has eight different background areas, enabling developers to create rounded gradient border effects.

Amin

You can achieve the following;

  • Create gradient animations. The tool allows you to generate gradient animations that transition between two or more colors.
  • You can include JavaScript code. If your customizable element needs JS code, you can always find and customize it from the control panel.
  • Live preview. You can view the changes to your code as you customize it.

You can copy-paste the code after customizing your border gradient effects to your liking.

Conclusion

When designing your web pages, you can use any of the above approaches to add a gradient border to your elements. The choice of approach may vary based on preference, skill level, and the nature of the element you are styling.

You may also use different approaches for different elements on the same web page.

Check out how to create a double border in CSS to improve your webpage’s visual appeal.

Источник

Как задать градиент для border в CSS?

Как задать градиент для border в CSS?

Рассмотрим как задать в CSS border gradient, это позволит вам создать на своём сайте красивый эффект градиентной рамки. В одной из предыдущих статей я подробно рассматривала как задать градиент в качестве фона.

Так вот, CSS 3 позволяет нам это сделать не только для фона, но и для рамки.

Линейный градиент

Для примера рассмотрим такой блок:

Чтобы задать ему размеры, отступы и так далее я допишу следующие CSS свойства:

Теперь нам нужно задать толщину рамки и её тип:

Для задания градиента допишем свойство border-image в css файле:

Здесь мы в скобках задаём значения цветов, которые будут идти сверху вниз.
Чтобы наше CSS свойство работало во всех браузерах допишем кроссбраузерные префиксы:

-moz-border-image: -moz-linear-gradient(#0B0E7F , #0B95DD);
-webkit-border-image: -webkit-linear-gradient(#0B0E7F , #0B95DD);

И последнее зададим CSS свойство:

Чтобы заданный градиент сместился или растянулся по всей границе.
В итоге весь CSS код задания border gradient будет выглядеть так:

Вот результат работы кода:

Особенности border gradient в CSS

  1. 1 В скобках мы можем задать не обязательно 2 цвета, их может быть больше. Для этого просто указываем значения цветов через запятую:
Читайте также:  Php mail set smtp port

border-image: linear-gradient( #0E9ADF 0%, #F4F955 20%, #0625F9 100%);
-moz-border-image: -moz-linear-gradient(#0E9ADF 0%, #F4F955 20%, #0625F9 100%);
-webkit-border-image: -webkit-linear-gradient(#0E9ADF 0%, #F4F955 20%, #0625F9 100%);

Направление градиента border gradient

Чтобы наш градиент для рамки шел не сверху вниз, а например, слева направо или по диагонали мы можем задать для него направление при помощи дополнительных параметров.

Параметры border gradient css

При задании градиента с кроссбраузерными префиксами этот пример пишется немного иначе.

-moz-border-image: -moz-linear-gradient(left, #0B0E7F , #0B95DD);
-webkit-border-image: -webkit-linear-gradient(left, #0B0E7F , #0B95DD);

В первом случае мы писали в каком направлении должен распространяться градиент, а во втором – куда он должен идти.
Пример для border gradient слева направо:

Источник

Градиентные границы в CSS

Доброго времени суток уважаемые хабровчане. Представляю вашему вниманию перевод статьи Криса Коера.

Допустим, вам нужна градиентная граница вокруг определенного элемента. И вы, такой, думаете:

  • Для этого не существует простого и очевидного CSS API.
  • Я просто сделаю элемент-обертку с линейно-градиентным фоном, а затем внутренний элемент заблокирует большую часть этого фона, за исключением тонкой линии заполнения вокруг него.

Выглядеть это будет как-то так:

Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero pariatur corporis quaerat voluptatum eos tempora temporibus nisi voluptates sed, exercitationem sequi dolore culpa incidunt accusamus, quasi unde reprehenderit ea molestias.
body < height: 100vh; margin: 0; display: grid; place-items: center; background: #222; >.module-border-wrap < max-width: 250px; padding: 1rem; position: relative; background: linear-gradient(to right, red, purple); padding: 3px; >.module

Если вам не нравится идея оберточного элемента, вы можете использовать псевдоэлемент, до тех пор, пока отрицательное значение z-индекса в порядке (этого не произошло бы, если бы было много вложений родительских элементов с их собственными фонами).

Вот пример Стивена Шоу, закрепляющий border-radius :

 

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent bibendum, lorem vel tincidunt imperdiet, nibh elit laoreet felis, a bibendum nisl tortor non orci. Donec pretium fermentum felis, quis aliquet est rutrum ut. Integer quis massa ut lacus viverra pharetra in eu lacus. Aliquam tempus odio adipiscing diam pellentesque rhoncus. Curabitur a bibendum est.

Но не забывайте полностью о border-image , возможно, самом бестолковом свойстве CSS всех времен. Вы можете использовать его, чтобы получить градиентные границы даже на отдельных сторонах:

 
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vero pariatur corporis quaerat voluptatum eos tempora temporibus nisi voluptates sed, exercitationem sequi dolore culpa incidunt accusamus, quasi unde reprehenderit ea molestias.

Использование как border-image , так и border-image-slice , вероятно, является самым простым синтаксисом для создания градиентной границы, но, к сожалению, это просто несовместимо с border-radius .

 
button < background: none; text-decoration: inherit; font-family: system-ui; font-size: 1rem; padding: 1rem 2rem; >.border-gradient < border-image-slice: 1; border-width: 2px; >.border-gradient-purple < border-image: linear-gradient(to left, #743ad5, #d53a9d); >.border-gradient-green < border-image: linear-gradient(to left, #00C853, #B2FF59); >body < height: 100vh; margin: 0; display: flex; justify-content: center; align-items: center; >div < width: 100%; text-align: center; >> div > div < width: 100%; padding: 1rem; >> .on-dark < background: #222; button < color: white; >>

Источник

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