CSS: border. Element Bounds


The CSS border property is used to create the border of an object, namely the thickness of the border, its color and style. This property is widely used in HTML. You can create various effects for better perception of the content on the page. For example, design a sidebar, website header, menu, etc.

1. CSS border syntax

border : border-width border-style border-color | inherit;
  • border-width - border thickness. You can set it in pixels (px) or use the standard values ​​thin, medium, thick (they differ only in width in pixels)
  • border-style - style of the displayed border. Can take the following values
    • none or hidden - cancels the border
    • dotted - dotted frame
    • dashed - frame made of dashes
    • solid - simple line (most often used)
    • double - double frame
    • groove - grooved 3D border
    • ridge, inset, outset - various 3D frame effects
    • inherit - the value of the parent element is applied
  • border-color - border color. Can be set using specific name colors or in RGB format (see names of html colors for the site)
Note

The values ​​in the CSS border property can be set in any order. The most commonly used sequence is “thickness style color”.

2. Examples with different CSS borders

2.1. Example. Different border design styles border-style

border-style: dashed
border-style: dashed
border-style: solid
border-style: double
border-style: groove
border-style: ridge
border-style: inset
border-style: outset

border-style: dotted

border-style: dashed

border-style: solid

border-style: double

border-style: groove

border-style: ridge

border-style: inset

border-style: outset

Четыре разных рамки

2.2. Пример. Изменения цвета рамки при наведении курсора мыши

Этот пример очень простой, но интересный. Он показывает, как можно использовать псевдокласс :hover и рамку CSS border для создания простых эффектов (например, для меню).

При наведении курсора мыши на блок цвет рамки изменится

Вот как это выглядит на странице:

2.3. Пример. Как сделать прозрачную рамку border

Рамку можно сделать прозрачной. Этот эффект редко, но иногда может быть очень полезен для веб-дизайнеров. Для задания прозрачности надо воспользоваться заданием цвета в виде RGBA (R, G, B, P) , где последним параметром задается прозрачность (вещественное число от 0.0 до 1.0)

Вот как это выглядит на странице:

3. Толщина границы: свойство border-width

Задает толщину линии. Ранее мы задавали ее в едином описании border.

Синтаксис CSS border-width

border-width : thin | medium | thick | значение ;
  • thin - тонкая толщина линии
  • medium - средняя толщина линии
  • thick - толстая толщина линии

Ниже приведены несколько примеров. Самым необычным будет - это разная толщина границы у каждой стороны.

border-width: thin
border-width: medium
border-width: thick
Разная толщина у границ

Вот как это выглядит на странице:

border-width: thin


border-width: medium


border-width: thick


Разная толщина у границ

4. Как сделать рамку border только с одного края (границы)

У свойства CSS border есть производные свойства для задания односторонних границ у элемента:

  • border-top - для задания рамки сверху (верхняя граница)
  • border-bottom - для задания рамки снизу (нижняя граница)
  • border-right - для задания рамки справа (правая граница)
  • border-left - для задания рамки слева (левая граница)

Эти границы можно совмещать, т.е. прописать для каждого направления свою рамку. Синтаксис точно такой же как и у border.

Также есть свойства

  • border-top-color - задание цвета верхний границы
  • border-top-style - задание стиля верхней границы
  • border-top-width - задание толщины верхней границы
  • и т.д. для каждого направления

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

/* Описание двух одинаковых стилей: */

4.1. Пример. Красивая рамка для выделения цитат

Пример рамки для цитаты

Вот как это выглядит на странице:

Пример рамки для цитаты

Примечание
Можно задать отдельную границу для каждой из сторон.

5. Как сделать несколько границ border у элемента html

Иногда требуется сделать несколько границ. Приведем пример

5.1. Первый вариант с несколькими границами

Вот как это выглядит на странице:

Есть второй способ через наложение теней.

5.2. Наложение теней для создания нескольких границ

Вот как это выглядит на странице:

6. Скругление углов у границ (border-radius)

Для создания красивых рамок используют свойство CSS border-radius (доступно только в CSS3). С помощью него можно делать скругления углов, что создает совсем другой вид. Например

7. Вдавленная линия CSS

Вдавленные линии эффектно могут смотреться на темном фоне, что подходит далеко не каждому сайту.


Вот как это выглядит на странице:

Для обращения к border из JavaScript нужно писать следующую конструкцию:

document.getElementById("elementID").style.border ="VALUE "

Приветствую всех читателей текущей публикации! Сегодня мы разберем с вами, как создается обводка текста css-средствами. Я расскажу вам, какие на данный момент существуют инструменты для реализации обводки вокруг текстового контента, как все это работает в различных браузерах и конечно же приведу конкретные примеры. А теперь давайте приступать к делу!

Обратимся к привычным инструментам

Долгое время, да и по сей день разработчики используют свойство text- shadow для создания контура вокруг символов. Но на самом деле названный элемент изначально был разработан для формирования теней вокруг текста.

Благодаря гибкому механизму управления слоями, с помощью text- shadow можно создать абсолютно разные эффекты: вдавленный или объемный, прозрачный или с градиентом текст и так далее. Конечно же данное свойство можно использовать и для реализации контуров.

Преимущество текущего инструмента состоит в том, что:

  • он привычен девелоперам в использовании;
  • корректно отображается во без исключения;
  • прост в использовании;
  • позволяет создавать различные эффекты для контента.

А теперь рассмотрим программную реализацию. В я создал простой заголовок первого уровня, а в стилях из основного указал цвет текста и параметры тени.

Пример создания черного контура

Mega super duper title

However, in this case the outline is practically invisible. Therefore, get ready for the fact that in this one you will have to create several layers:

text-shadow: 0 0 2px #010010, 0 0 3px #010010, 1px 1px 2px #010010, 2px 2px 2px #010010, 3px 3px 1px #010010;

Despite the existence of this mechanism, another one was created, focused specifically on the implementation of the contour around the symbols.

A new tool to solve the problem

Among the properties of css3 style sheets, a new one has appeared, the name of which is -webkit-text-stroke. The named property works only in browsers created on the engine Webkit. This means, unfortunately, it will not be displayed in Firefox and Internet Explorer.

I want to warn you right away that the current tool is in the so-called experimental stage. You won't even find it in the W3C specifications. Although it was previously described under the name text-outline, and then removed from the documentation.

To Work with -webkit-text-stroke quite simple, since it functions just like border. To set a specific color, add -color to the above name, and -width to determine the thickness. However, as with border, you can use a shorthand style description. Those. First specify the thickness of the stroke, and then its color. For better understanding material let's look at an example.

Example implementation of a bright outline

Mega super duper title

As you can see, in this case the stroke looks neat and is much easier to create.

Thanks to this property, you can create not only the usual stroke, but also make it translucent.

However, do not forget that when using text-stroke, you should take care of the correct display of text content in other browsers.

A few words about generators

If you don’t know what code to write to implement a particular design, then use online generators. As an example I can give a link http://protocoder.ru/css/strokeTextGen. By clicking on it, you can generate a certain type of outline for the text, and also look at the resulting css code in the constructor below.

On this note, my publication has come to an end. If you liked the material presented, please please me with your subscription requests, and also don’t be greedy and share interesting links with colleagues and friends. Bye bye!

Best regards, Roman Chueshov

Read: 79 times

3.5 out of 5

Do you think it is possible with a couple of tags and pure CSS make a scalable triangle? What about the pentagon? But such a star? I think many people think not. Actually it is possible.

So, today we have a post-experiment. We will play with the well-known CSS property - border (and all that relate to it). During the experiment we will look at how to make some simple polygons, a star and look at one case where these techniques can be used in practice. Go!

Simple geometric shapes

So let's start with simple examples. Do you know how to draw a triangle? using HTML and CSS? And like this:

HTML
CSS
.trapezoid ( vertical-align: text-bottom; )

Trapezoid,
.polygon ( display: -moz-inline-block; )

Polygon,
.trapezoid ( margin:0; padding: 0; background: none; )

Polygon ( width: 10em; height: 10em; border: none; display: inline-block; text-align: center; )
.trapezoid (
display: inline-block; width: 1px; height: 0; margin: 0 auto;
border-left: 5em solid transparent; border-right: 5em solid transparent;
}

Polygon .aa ( border-bottom: 10em solid; border-top: none; )

Polygon.r2 ( height: 0em; )

Polygon.r3 ( height: 8.66em; )
.polygon.r3 .trapezoid ( border-width: 8.66em 5em; )

div.eg ( width: 10em; background: #FFF; margin: 0 0; padding: 1em; )
div.eg .polygon ( display: block; margin: 0 auto; )

R3 ( color: red; font-size: 0.5em; )

Star

HTML


Star


CSS
#star(
width: 15em;
height: 14.27em;
position: relative;
}

#star span,
#star(
display: block;
}

#top(
width: 0;
height: 0;
margin: auto;
border-right: 4.64em solid transparent;
border-left: 4.64em solid transparent;
border-bottom: 14.27em solid;
}

#center(
width: 5.7em;
border-right: 4.65em solid transparent;
border-left: 4.65em solid transparent;
border-top: 3.36em solid;
height: 0;
position: absolute;
top: 5.46em;
left: 0;
z-index: 100;
text-align: center;
}

#bottom(
position: absolute;
bottom: 0;
left: 2.852em;
border-right: 4.635em solid transparent;
border-left: 4.635em solid transparent;
border-bottom: 3.4em solid #fff;
width: 0;
height: 0;
}

#center span(
margin-top: -2em;
color: #000;
font-weight: bold;
}

a#star:hover #center span(
color: #fff;
background-color: transparent;
}

a#star(
color: #f90;
background-color: transparent;
}
a#star:hover(
color: #fc3;
background-color: transparent;
}

Some more examples

  • Christmas tree and unusual layout by Eric Meyer;
  • Tiles and menus from the chief technologist of Technocracy;

To control the border of an element, use the generic border property. This property allows you to set the thickness, style, and color of an element's border in a single declaration.

These three properties (border thickness, border style, and color) can be set in a single declaration. Here's an example:

Borders in CSS

A div block with a 3px border in red.

You can specify a border style on only one side of an element. To do this, use the properties border-top (top border), border-right (right border), border-bottom (bottom border), border-left (left border).

Borders in CSS

A div with different borders.

In this example, each side of the block has a different border thickness, style, and color.

Think about how to CSS help you can create a shape like this:

Border values ​​- thickness, style and color - can be set separately using special properties.

  • border-style - border style.
  • border-width - border width.
  • border-color - border color.

Let's consider each of the values ​​separately.

border-style property Border style.

The border-style property sets the style of the border. In CSS, in HTML differences, the border of an element can be not only solid. The following values ​​are accepted for the border style:

  1. none - no border (default).
  2. solid - solid border.
  3. double - double border.
  4. dashed - dotted border.
  5. dotted - a border made of a series of dots.
  6. ridge - "ridge" border.
  7. groove - "groove" border.
  8. inset - depressed border.
  9. outset - extruded border.

Examples of what they look like.

no border (none)


solid border


double border


border of a series of dots (dotted)


dashed border


groove border


ridge border


indented border (inset)


extruded border (outset)

By the way, if you set the border color to black for the ridge frame, you will get this result.

A div block with a black border and ridge style.

The frame looks solid, but that's because the ridge style is created by adding a black shadow effect, and the black effect is not visible on a black frame.

Using the border-style property, the border style can be set not only for all sides of the block. It is possible to set multiple values ​​for one border-style property; depending on the number of values, the border style will be assigned to a different number of sides of the block. You can set one, two, three or four values. Let's look at examples for each case.

One value (solid) - the border style is set for all sides of the block.


Two values ​​(solid double) - the first value set the style for the top and bottom sides, the second for the side.


Three values ​​(solid double dotted) - the first value for the top side, the second for the sides, the third for the bottom.


Four values ​​(solid double dotted dashed) - each value for one side clockwise starting from the top.

The border-width property. Border thickness.

To set the width of an element's border, use the border-width property. The border thickness can be specified in any absolute units of measurement, for example in pixels.

Like the border-style property, the property can also be set to one to four values. Let's look at examples for each case.



Example code:

Border thickness in CSS

One value (2px) - the border thickness is set for all sides of the block.

Two values ​​(1px 5px) - the first value set the thickness for the top and bottom sides, the second for the side.

Three values ​​(1px 3px 5px) - the first value for the top side, the second for the sides, the third for the bottom.

Four values ​​(1px 3px 5px 7px) - each value for one side clockwise starting from the top.

Also for the border-width property there are values ​​in the form keywords. There are three in total:

  • thin - thin border;
  • medium - average thickness;
  • thick - thick border;

Border thickness: thin.


Border thickness: medium.


Border thickness: thick.

The border-color property. Border color.

To control the border color, use the border-color tool. The colors for this property can be set using any method described in the article "Colors in CSS", namely:

  • Hexadecimal notation (#ff00aa) of the color.
  • RGB format- rgb(255,12,110) . RGBA format for CSS3.
  • HSL formats and HSLA for CSS3.
  • Color name, for example black. Full list Color names are given in the CSS color names table.

The border-color property can also have one to four values ​​and treats them similarly to the previous properties.

One value (red).


Two values ​​(red black).


Three values ​​(red black yellow).


Four values ​​(red black yellow blue).

Now let's return to the problem stated above and draw a figure:

Here is the code that draws such a figure, only larger in size:

Border thickness in CSS

Setting values ​​for sides separately

It was mentioned above that you can specify border property values ​​for only one side of a block. There are properties for these purposes:

  • border-top (top border)
  • border-right
  • border-bottom
  • border-left (left border)

Let me remind you that for all properties three values ​​​​are specified (thickness, style and color) in any order. But there are properties that allow you to set the thickness, color and style for each side separately. The writing of these properties is derived from the above.

Top border options (border-top).

  • border-top-color - sets the color of the element's top border.
  • border-top-width - sets the thickness of the element's top border.
  • border-top-style - sets the style of the element's top border.

Right border options (border-right).

  • border-right-color - sets the color of the element's right border.
  • border-right-width - sets the thickness of the element's right border.
  • border-right-style - sets the style of the element's right border.

Bottom border options (border-bottom).

  • border-bottom-color - sets the color of the element's bottom border.
  • border-bottom-width - sets the thickness of the element's bottom border.
  • border-bottom-style - sets the style of the element's bottom border.

Left border options (border-left).

  • border-left-color - sets the color of the left border of the element.
  • border-left-width - sets the thickness of the element's left border.
  • border-left-style - sets the style of the left border of the element.

An example of using these properties:

Border thickness in CSS

In this example div block First, the borders are set to 3px thick and solid style for all sides. Then:
  • the color of the top border was redefined to red using the border-top-color property,
  • using the border-right-width property, the thickness of the right border is set to 10px,
  • using the border-bottom-style property, the style of the bottom border is redefined as double,
  • Using the border-left-color property, the left border color is set to blue.

The border-radius property. Rounding border corners.

The border-radius property is intended to round the corners of an element's borders. This property appeared in CSS3 and works correctly in all modern browsers, with the exception of Internet Explorer 8 (and older versions).

The values ​​can be any numbers used in CSS.

Border-radius property: 15px.

If the block frame is not specified, then the fillet occurs with the background. Here is an example of a rounded block without a border, but with a background color:

Border-radius property: 15px.

There are properties for rounding each individual corner of an element. This example uses them all:

Border-top-left-radius: 15px; border-top-right-radius: 0; border-bottom-right-radius: 15px; border-bottom-left-radius: 0;

Border-radius property: 15px.

Although this code can be written in one declaration: border-radius : 15px 0 15px 0 . The fact is that the border-radius property can be set from one to four values. The table below outlines the rules that govern such announcements.

Having carefully studied this table, you can understand that the shortest entry for the desired style will be like this: border-radius : 15px 0 . There are only two meanings.

A little practice

Drawing a lemon using CSS.

Here is the code for such a block:

Margin: 0 auto; /* Center the block */ width: 200px; height: 200px; background: #F5F240; border: 1px solid #F0D900; border-radius: 10px 150px 30px 150px;

We have already drawn the figure:

Now let's leave a triangle from it:

The triangle code is:

Margin: 0 auto; /* Center the block */ padding: 0px; width: 0px; height: 0; border: 30px solid white; border-bottom-color: red;

CSS border An element is one or more lines surrounding the element's content and its padding. The border is specified using the shorthand border property. The frame style is set using three properties: style, color And width.

Decorating frames and borders of HTML elements using CSS properties

1. Border-style

By default, borders are always drawn on top of the element's background, with the background extending to the outer edge of the element. The frame style determines its display; without this property, frames will not be visible at all. For an element, you can set a border for all sides simultaneously using the border-style property, or for each side separately using the border-top-style qualifying properties, etc. Not inherited.

border-style
(border-top-style, border-right-style, border-bottom-style, border-left-style)
Values:
none The default value means no frame. Also removes the border of an element from a group of elements with a set value of this property.
hidden Equivalent to none .
dotted
dotted
dashed
dashed
solid
solid
double
double
groove
groove
ridge
ridge
inset
inset
outset
outset
{1,4}
Listing four different styles for an element's border at once, just for the border-style property:
(border-style: solid dotted none dotted;)
initial
inherit

Syntax

P (border-style: solid;) p (border-top-style: solid;)

2. Frame color border-color

The property sets the color of the frames on all sides at the same time. Using the clarifying properties, you can set a different color for the border of each side of the element. If no color is specified for the frame, it will be the same as the color of the element's text. If the element has no text, the border color will be the same as the parent element's text color. Not inherited.

border-color
(border-top-color, border-right-color, border-bottom-color, border-left-color)
Values:
transparent Installs transparent color for the frame. At the same time, the width of the frame remains. Can be used to change the border color when hovering the mouse over an element to avoid the element being displaced.
color The color of the frames is set using the values ​​of the property.
(border-color: #cacd58;)
{1,4}
Simultaneous transfer of four different colors for element borders, only for the border-color property:
(border-color: #cacd58 #5faf8a #b9cea5 #aab238;)
initial Sets the property value to the default value.
inherit Inherits the property value from the parent element.

Syntax

P (border-color: #cacd58;)

3. Border-width

The frame width is specified using length units or keywords. If the border-style property is set to none and the element's border is set to some width, then in this case The frame width is set to zero. Not inherited.

Syntax

P (border-width: 2px;)

4. Setting a frame with one property

The border property allows you to combine the following properties: border-width , border-style , border-color , for example:

Div ( width: 100px; height: 100px; border: 2px solid gray; )

In this case, the specified properties will be applied to all borders of the element simultaneously. If any value is not specified, the default value will take its place.

5. Setting a frame for one border of an element

In cases where you need to specify a different border style for an element, you can use the shorthand notation for the corresponding border.
The properties listed below combine the following properties into a single declaration: border-width , border-style , and border-color . The list of properties is specified in a given order, while one or two values ​​can be skipped, in which case their values ​​will take on the default values.

The style of the top border is set using the border-top property, the bottom - border-bottom , the left - border-left , and the right - border-right .

Syntax

P (border-top: 2px solid grey;)

6. External contour outline

The property specifies an outer border around elements (i.e. outside the normal border). The main purpose of this property is to highlight an element. Unlike the border property, applying this property does not affect the size or position of the element, because the outline is displayed on top of the element's box, which in turn can result in the element's outer padding and adjacent areas overlap.

Also, the outer contour, unlike the element’s frame, surrounds the element on all sides, framing it entirely.

The outer outline is always rectangular and does not follow the border of the block for which border-radius is specified.

The outline property allows you to combine the following properties: outline-color , outline-style , outline-width . If any value is not specified, the default value will take its place.

Div ( width: 100px; height: 100px; outline: #cacd58 solid 2px; )

6.1. outline-style

Line view outer contour is set similarly to the style of the element's frame. Not inherited.

Syntax

P (outline-style: ridge;)

6.2. Outer outline color outline-color

The color of the outer contour can only be specified when set value outline-style. Not inherited.

Syntax

P ( outline-style: ridge; outline-color: silver; )

6.3. Outer outline thickness outline-width

The thickness of the outer contour line is set similarly to the thickness of the element's frame. Not inherited.

Syntax

P ( outline-style: dotted; outline-width: 5px; )







2024 gtavrl.ru.