- How to create a colored border around text with HTML and CSS
- Border CSS
- Add a border using the style attribute
- Add a border using a CSS class
- Related information
- CSS Text Stroke/Outline
- Using 4 Text Shadows
- Using 8 Box Shadows
- Using -webkit-text-stroke Property
- Using SVG Filters
- Black Outline
- Colored Outline
- Using Corners Text-Shadow
- Using Corners and Diagonals Text-Shadow
- Using Text Stroke
- Using SVG Filter (Black Outline Only)
- Using SVG Filter (All Colors Supported)
- Examples
- Как сделать боковые линии от текста в css?
- 3 ответа 3
- Связанные
- Похожие
- Подписаться на ленту
How to create a colored border around text with HTML and CSS
Using borders, you can add a box around text, and set or change the border to nearly any color. A border in your HTML (hypertext markup language) page helps bring attention to a section of text or surround any other HTML elements. Borders are added to HTML using CSS (cascading style sheets).
Border CSS
Border CSS has properties for line type (solid, dotted, etc.), line width, and line color. The following table elaborates on the details of each and which values are acceptable to make them work properly.
CSS Border Property | Valid Values | Example |
---|---|---|
border (all sides) border-top (top line only) border-right (right line only) border-bottom (bottom line only) border-left (left line only) | Any valid combination of the properties below. | dotted thin black |
border-style (all sides) | solid dotted dashed double groove ridge inset outset none hidden | solid |
border-width (all sides) | width, specified in px, pt, cm, em width, specified as thin, medium, or thick | 3 px |
border-color (all sides) | color, specified as color code color, specified as named color | #FF00FF |
Add a border using the style attribute
HTML tags can be formatted using a style attribute. To add a border using the style attribute, add the border CSS inside the quotes after style=.
In the example below, we surrounded a paragraph ( ) with a solid red border that is 3 pixels wide.
First example with text surrounded by a red border.
This example also has multiple lines.
To create the example above, the code below is used.
<p style="border-width:3px; border-style:solid; border-color:#FF0000; padding: 1em;">First example with text surrounded by a red border.
This example also has multiple lines.p>
In the code above, the CSS is defining the border size («px» short for pixel), style type, and border color. The style of the border is how the border appears on the screen. In our example, we used the «solid» border style. The border color defines the color you want to use for the border. In the example above, the color code #FF0000 is used, which is the color code for red.
A border can also be applied to only one side. For example, with the heading of this page, we have a grey underline. This line is actually a border, achieved with the CSS code border-bottom: 1px solid #93B0D2;.
Placing the CSS formatting inside the style attribute can be applied to other HTML tags, such as the div tag or span tag. In the example below, a border is added to a single word using the span tag.
Here is a second example with a bordered word , with different styles applied to the top, bottom, left, and right.
To create the example above, the following code is used.
<span style="border-top:thick green solid;border-bottom:thick green double;border-left:4px #2330C4 dotted; border-right:thin #2330C4 dotted;padding-left:2px;padding-right:2px;">wordspan>
Add a border using a CSS class
The appearance of elements on a web page may also be defined with inline CSS. Inline CSS is defined in your HTML document, in the element. Or, you can define the CSS in an external file with the .css extension. Then, you can link to this file from any HTML page, and elements in that document can use the CSS styles. For example, with the CSS code below, a new class named «borderexample» is created that can be applied to any HTML tag.
Using the code above, if you want to apply this border style to an HTML paragraph or word, you can type something similar to the example below.
<p class="borderexample">Here is an example of a border created using CSS.p> <p>The class can also be <span class="borderexample">usedspan> on the span tag.p>
On your web page, the code above would look like the example below.
Here is an example of a border created using CSS.
The class can also be used on the span tag.
Related information
CSS Text Stroke/Outline
Developing content for the web, you may come across the requirement of adding an outline to the text. This article will demonstrate different possibilities for creating text outlines via CSS and their limitations.
Let’s start with the text-shadow property. You may be tempted to think that a plain text-shadow should fulfill our requirement but that is not the case. While it tries to provide a good approximation, the browser has to render the text multiple times and it is not perfect at corners. Let’s see it in action.
Using 4 Text Shadows
Let’s create a text and add 4 text shadows to it, one for each direction.
Zooming in on the result, you can see the corners are not filled in and some curves lack the outline.
Using 8 Box Shadows
We can improve the results by adding diagonal shadows to fill in the corners. The «1.41» values are there to make the diagonal shadows the correct distance. This value is easy to calculate with the following formula: √(R² ÷ 2) (where R is the radius of the stroke). To put it more simply, take the desired stroke width (in this case 2), multiply it by itself (2 × 2 = 4), divide that by 2 (4 ÷ 2 = 2), and then take the square root (√ 2 = 1.41).
This required the browser to render the text 9 times. The shadows are improved but still not perfect. If you zoom into the corners, you can still observe steps at the corners.
This technique performs particularly poorly in the case of thicker strokes. The diagonal stroke distances have been calculated in the same way: √(9² ÷ 2) = 6.36
Using -webkit-text-stroke Property
CSS offers a dedicated property named —webkit-text-stroke which is capable of applying perfect text outline.
This property has fairly good support across browsers. But to be on the safe side, we can use the text-shadow as a fallback, and only use the -webkit-text-stroke if the browser supports it.
.text-outline < text-shadow: 1.41px 1.41px black, 2px 0 black, 1.41px -1.41px black, 0 -2px black, -1.41px -1.41px black, -2px 0 black, -1.41px 1.41px black, 0 2px black; >@supports (-webkit-text-stroke: 1px black) < .text-outline < -webkit-text-stroke: 2px black; text-shadow: none; >>
This will render the perfect outline on browsers that support it, and the fallback text-shadow outline on browsers that do not.
Zomming-in on the corners, you can observe there are no steps or missed curves — if. your browser supports text-stroke property.
Using SVG Filters
SVG filters are a very handy tool for visually modifying content. There are many filters offered out of the box with flexible, customizable properties. You can apply the filters step-by-step and monitor the output of each. SVG Filters enable theoretically infinite possible effects for the text.
For this article, we will build two outline filters step by step. The first one will build an outline that supports black color only while the second one will be able to draw an outline of any color of your choice.
Note: SVG filter does not quite provide an even stroke all the way around the text. It also does not have any better browser support than -webkit-text-stroke , making the -webkit-text-stroke the best option for most websites, with the text-shadow fallback.
Black Outline
Let’s build the first filter. We can create an outline by taking the text’s alpha-channel/opacity (visually exact text but black colored only as all the other colors are dropped), increasing its thickness (dilating it), and placing the original text on top of it.
We render the original text.
We define the boilerplate of the filter.
Step 1: Take the source alpha only of the text input using the feMorphology filter.
Note that we are adding code to the original boilerplate step by step, and not defining a new filter.
Step 2: Dilate (make bigger) the result of source alpha. We will dilate it with a radius of 2. This dilution will become the thickness of the outline. You can adjust the value as per your need.
Step 3: Merge the dilated text and the original text. Original text will be placed on top of the alpha. This is the last step and the end visual result will be our text with an outline. We have the final code of the filter and its visual output.
You can now use this filter on the text (or any other element) to get a black outline, with a thickness of your choice. Applying the filter requires only setting the element’s filter attribute in CSS.
Note: If you need to put the definition of your SVG Filters in the markup of your page without them showing up as text (just like for this article), make sure you wrap them in an absolutely positioned having a width and height of 0 pixels. You may be tempted to wrap in a with display set to none but the filter stops working in that case.
Colored Outline
The step-by-step process behind the second filter will be as follows
- Create a replica of text with increased/dilated thickness
- Create a solid rectangle with the color of your choice
- Compose the text and rectangle together so that only the overlapping pixels of the rectangle are extracted as output. This will essentially complete the process of creating a colored outline
- Merge the text and colored outline into one. The result will be the original text with an outline of the selected color
Let’s build the second filter — one that supports any color for the outline. Here is our original text
We define the boilerplate of the filter.
Step 1: Add an feMorphology filter that takes the source alpha channel (opacity) of the input and dilates it with a radius of 2. This will create a replica of text but with increased thickness. The result is stored in “Dilated”.
Step 2: Add an feFlood filter to create a solid rectangle. We provide our selected color as a hexcode with the input named flood-color. The result gets stored in “OutlineColor”.
Step 3: Compose the source alpha and the rectangle together using feComposite filter. The feComposite filter uses the «in» operation, which takes each pixel from the «in» attribute. If it overlaps a pixel in the «in2» attribute, then the pixel from «in» is used. Since we have just used the alpha channel in feMorphology, this essentially turns the «in2» attribute into a mask for the «in» attribute, effectively creating a larger version of our original text in a solid color of our choice. This gets stored in «Outline».
Step 4: Merge the outline and the text. After composing the solid rectangle with our outline mask, we have our colored outline. The last step is to merge the outline and text together using feMerge filter.
Now we can apply it to our element using CSS.
Here is the complete codepen.
Using Corners Text-Shadow
UnusedCSSUsing Corners and Diagonals Text-Shadow
UnusedCSSUsing Text Stroke
UnusedCSSUsing SVG Filter (Black Outline Only)
UnusedCSSUsing SVG Filter (All Colors Supported)
UnusedCSS
* < font-family: sans-serif; >body < height: 100vh; margin: 0; >.container < display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 24px; >.main-text < font-size: 120px; color: #48abe0; >.text-outline < text-shadow: 2px 0 black, 0 -2px black, -2px 0 black, 0 2px black; >.text-outline-diagonal < text-shadow: 1.41px 1.41px black, 2px 0 black, 1.41px -1.41px black, 0 -2px black, -1.41px -1.41px black, -2px 0 black, -1.41px 1.41px black, 0 2px black; >.text-outline-stroke < -webkit-text-stroke: 2px black; >.text-outline-svg-black < filter: url(#outlineBlack); >.text-outline-svg-colored
Examples
See the Pen text stroke by Freddy Gomez (@dajama) on CodePen.
Stroked text with decoration
A fancy mill using text stroke and animation
A very subtle text stroke with a background image
UnusedCSS helps website owners remove their unused CSS every day. Sign Up to see how much you could remove.
You Might Also Be Interested In
Как сделать боковые линии от текста в css?
Как лучше сделать вот такие линии причем вначале линия более жирная.
3 ответа 3
Эмуляция вашего браузера конечно-же. А о том, что — У меня во всех браузерах немножко по-другому мой код отображается. , Немножко не понятно, о чем сейчас речь.
html, body < height: 100%, margin: 0; padding: 0; >div < display: flex; flex-flow: row nowrap; justify-content: center; padding: 2rem 1rem; font: 300 1.6rem sans-serif; color: #f6f6f6; text-transform: uppercase; text-align: center; border-bottom: 1px solid #fff; background: #373737; >div::before, div::after < content: ''; display: inline-block; flex: 1 0 auto; align-self: flex-end; height: 3px; margin: 0 0.3em 0.25em 0.3em; background: 100% center / 1.8em 2.75px no-repeat linear-gradient(to right, #f6f6f6 0%, #f6f6f6 100%), 100% center / 1px 1px repeat-x linear-gradient(to right, #f6f6f6 0%, #f6f6f6 100%); box-shadow: inset 0 0 1px 1px #37373740; >div::after
body < margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background-color: #212121; color: white; >div < width: 70%; display: flex; >div::before, div::after < content: ''; display: block; flex-grow: 1; height: inherit; border-bottom: 1px solid white; >span < display: flex; justify-content: space-around; align-items: flex-end; line-height: 0.8; font-size: 1.5rem; >span::before, span::after < content: ''; display: block; width: 50px; height: 2px; background-color: white; transform: translateY(25%); border-radius: 0.3rem; >span::before < margin-right: 0.4rem; >span::after
Связанные
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.27.43548
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.