Html text border padding

Отступы и рамки в CSS с помощью параметров margin, padding и border

Здравствуйте, уважаемые читатели блога webcodius.ru! Сегодня мы продолжим изучение каскадных таблиц стилей или CSS. В прошлых статьях мы уже рассмотрели в общих чертах блочную верстку сайта. В результате у нас стали получаться вполне профессиональные web-страницы, но чего-то им не хватает. А не хватает им скорей всего отступов и рамок. Сегодня мы и займемся рассмотрением стилевых правил margin, padding и border, которые позволяют задавать отступы и рамки для html-элементов.

Параметры отступов в CSS

С помощью каскадных таблиц стилей существует возможность задавать отступы двух видов.

1. Внутренний отступ — это расстояние от воображаемой границы элемента до его содержимого. Величина расстояния задается с помощью параметра padding. Такой отступ принадлежит самому элементу и находится внутри него.

2. Внешний отступ — расстояние между границей текущего элемента веб-страницы и границами соседних элементов, либо родительского элемента. Размер расстояния регулируется свойством margin. Такой отступ находится вне элемента.

отступы и границы

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

Внутренние отступы в CSS с помощью padding (top, bottom, left, right)

Свойства стиля padding-left, padding-top, padding-right и padding-bottom позволяют задать величины внутренних отступов, соответственно, слева, сверху, справа и снизу элемента web-страницы:

padding-top | padding-right | padding-bottom | padding-left: значение | проценты | inherit

Величину отступа можно указывать в пикселах (px), процентах (%) или других допустимых для CSS единицах. При указании процентов, значение считается от ширины элемента. Значение inherit указывает, что оно наследуется от родителя.

Например, для текущего абзаца я применил правило стиля, задающий левый отступ 20 пикселей, верхний отступ 5 пикселей, справа отступ 35 пикселей и снизу 10 пикселей. Запись правила в файле каскадных таблиц стилей будет выглядеть следующим образом:

p.test padding-left:20px;
padding-top:5px;
padding-right:35px;
padding-bottom:10px
>

Сборное правило padding позволяет указать отступы сразу со всех сторон элемента веб-страницы:

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

  • если указать одно значение, то оно установит величину отступа со всех сторон элемента страницы;
  • если указать два значения, то первое задаст величину отступа сверху и снизу, а второе — слева и справа;
  • если указать три значения, то первое определит величину отступа сверху, второе — слева и справа, а третье — снизу;
  • если указаны четыре значения, то первое установит величину отступа сверху, второе — справа, третье — снизу, а четвертое — слева.

Таким образом правило CSS приведенное выше можно максимально сократить и записать следующим образом:

Читайте также:  Css vertical center table cell

Свойство margin или внешние отступы в CSS

Атрибуты стиля margin-left, margin-top, margin-right и margin-bottom позволяют задать величины внешних отступов, соответственно, слева, сверху, справа и снизу:

margin-top | margin-right | margin-bottom | margin-left: |auto|inherit

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

Величину отступа можно указывать в пикселах (px), процентах (%) или других допустимых для CSS единицах:

Значение auto означает, что размер отступов будет автоматически рассчитан браузером. В случае использования процентной записи, то отступы рассчитываются в зависимости от ширины родительского контейнера. Причем это относится не только к margin-left и margin-right, но и для margin-top и margin-bottom отступы в процентах будут рассчитываться в зависимости от ширины, а не высоты контейнера.

В качестве значений внешних отступов допустимо применять отрицательные величины:

Если при положительных значениях отступов соседние элементы отодвигаются, то при отрицательном значении соседний блок наедет на элемент для которого мы задали такой отрицательных отступ.

Внешние отступы мы также можем указать с помощью атрибута стиля margin. Он задает величины отступа одновременно со всех сторон элемента web-страницы:

Данное свойство в случае задания одного, двух, трех или четырех значений отступов подчиняется тем же законам, что и правило padding.

Параметры рамки с помощью свойства border

При настройке рамок существует три типа параметров:

  • border-width — толщина рамки;
  • border-color — цвет рамки;
  • border-style — тип линии с помощью которой будет нарисована рамка.

Начнем с параметра толщины рамки:

border-width: [значение | thin | medium | thick] | inherit

Толщину рамки можно задавать в пикселях, либо в других доступных в css единицах. Переменные thin, medium и thick задают толщину рамки в 2, 4 и 6 пикселей соответственно:

Как и для свойств padding и margin, для параметра border-width разрешается использовать одно, два, три или четыре значения, задавая таким образом толщину рамки для всех сторон сразу или для каждой по отдельности:

border-width: 5px 3px 5px 3px

Для текущего абзаца сделаем толщину верхней рамки 1px, правой 2px, нижней 3px, а левой 4px с помощью правила

С помощью атрибутов стиля border-left-width, border-top-width, border-right-width и border-bottom-width можно задавать толщину, соответственно, левой, верхней, правой и нижней сторон рамки:

Следующий параметр border-color с помощью которого можно управлять цветом рамки:

border-color: [цвет | transparent] | inherit

Свойство позволяет задать цвет рамки сразу для всех сторон элемента или только для указанных. В качестве значения можно использовать принятые в html для цветов способы их задания: шестнадцатеричный код, ключевые слова и т.д.:

Значение transparent устанавливает прозрачный цвет рамки, а inherit наследует значение родителя. По умолчанию, если цвет рамки не задан, то будет использоваться тот, который используется для шрифта внутри данного элемента.

С помощью атрибутов стиля border-left-color, border-top-color, border-right-color и border-bottom-color можно задать цвет, соответственно, левой, верхней, правой и нижней сторон рамки:

И последний параметр border-style задает тип рамки:

border-style: [none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset] | inherit

Тип рамки можно указывать сразу для всех сторон элемента или только для указанных. В качестве значений можно использовать несколько ключевых слов. Вид будет зависеть от используемого браузера и толщины рамки. Значение none используется по умолчанию и не отображает рамку и ее толщина задается нулевой. Значение hidden имеет тот же эффект. Получаемая рамка для остальных значений в зависимости от толщины приведена в таблице ниже:

Читайте также:  Script php order by

Источник

CSS Borders, Padding & Margins

The CSS Box model is essentially a rectangular box model that is used on sites to manipulate design and appearance, ranging from margins, borders, padding and content. These properties are relevant to the CSS Box:

  • Margin: by establishing a margin a free space is created around some element, thus eliminating the elements in the area outside the border; the margin is transparent
  • Borders: represents the edge of a CSS box, which extends around the pudding and the content, the margin is 0, being invisible, but it is possible to set the style, thickness or color of the border
  • Padding: is the lower edge of the CSS box, namely the outer edge of the content box and the edge of the edge of the border; the transparency is transparent
  • Content: is the content of the CSS box, where both the images and the text are inserted

We use the properties height and weight to set the size of an item so it can be rendered correctly in all browsers. It is very important to know how to set them, because inside the content is the text, pictures, tables and other items representative of nested child items.

Here’s an example of the above:

    .ex1 < width:300px; background-color: DarkSalmon; padding:0px; border:0px; margin:0px; >.ex2 < width:300px; background-color: DarkSalmon; padding:10px; border:5px solid brown; margin:30px; >.ex3 

CSS Box Model

the first example

the second example

the third example

CSS Margin

Through these properties, we can create a space around the elements, pushing upwards against other cassettes. Individual properties, which give us complete control over the margins: the left edge, the right edge, the top edge and the lower edge.

Margin – single side style

We can use the margin specifying property for each element: margin-left, margin-right, margin-top, margin-bottom. These properties can have the following values: auto, length, percent, initially and inherit. Attention! negative values are not preconditions.

     

The margin property

The margin property

CSS Borders

As I have already said, the edge of a CSS box extends around padding and content. The property allows you to set the border color of an element, width and style. These can be divided into many properties:

  • Border-top, border-right, border-bottom, border-left (set the style, thickness, and color of a portion of the edge)
  • Border-style, border-color, border-width (set the style, thickness or color individually, but for all four sides of the border)
  • Border-top-width, border-top-style, border-top-color (individually set one of the three properties of one side of the edge)

Borders with style

Values: none, solid, dotted, hidden, dashed, double, ridge, groove, inset, outset

Borders with color

This color property allows us to set the color of the four curves. The color can be set as follows: rgb (mention rgb values in the palette), name (mention any color name in the palette), hex (a hexagonal value) and transparency.

Border widths

This property specifies the width of the edges. The property can be set as pixels, cm, pt, ems using the three default values: thin, medium or thick.

Читайте также:  Events

Values: thin, medium, thick, length

Borders – single side style

You can set a different border style for just one side, or more. So, there is this property to specify the pattern of each border: border-left-style, border-right-style, border-top-style, border-bottom-style

Values: dotted, dashed, solid, double, groove, inset, outset, none

In the example below, we will use several types of values:

   body < font-size: 60%; color: grey; margin: 5; padding: 5; >p < padding: 3em; margin: 1em; >code < font: 1em/1.5 Courier; >#ex1 < border: 1px solid; >#ex2 < border: 1px dotted; >#ex3 < border: 2px dashed #ccc; >#ex4 < border: solid; border-width: 2px 6px 12px 18px; >#ex5 < border: 5px; border-style: solid dotted dashed solid; >#ex6 < border: 5px solid; border-color: black darksalmon darksalmon darksalmon; >#borderCollie 

SOLID

DOTTED

DASHED

SOLID - with 2px 6px 12px 18px

SOLID DOTTED DASHED SOLID

SOLID - with black darksalmon darksalmon darksalmon

CSS Padding

Outside the content area of any element, we find the lining that is between the contents and any borders. To set the lining, we use the filler property.

Padding – single side style

We can use the property to specify the lining for each part of an element: padding-left, padding-right, padding-top, padding-bottom. To fill, we can use the following values: length, inherit and percentage. Attention! negative values are not allowed.

     

The padding property

The padding property

CSS Outlines

The contour of a CSS box looks like a border, but it is not part of the box. Practically, it behaves like a border, but it is sketched on the top of the box without moving to the size of the box. This line is drawn around the elements, beyond borders. It has the following contour properties: outline-width, outline-color, outline-style, outline-offset.

Outline width

This property of the contour width determines the contour width, having the following values: , , , .

Outline color

With this property, the outline-color, we can set the contour color. It can be set by the following: rgb (mention rgb values in the palette), name (mention any color name in the palette), hex (a hexagonal value) and invert (a color reversal is performed).

Outline style

This property, the outline-style, defines the sketch style through its own values.

Values: auto, solid, dotted, dashed, groove, inset, outset, ridge, none

In the example below, we will use several types of values :

   body < margin: 10px; padding: 15px; >h1 < font-size: 30px; >pre < padding: 30px; border: 10px double; outline: 10px solid bisque; margin: 30px 0; >p < font-size: 25px; outline-color: greenyellow; outline-style: dashed; outline-width: thick; margin: 50px 0; >p b 

CSS outlines

CSS outlines

The contour of a CSS box looks like a border, but it is not part of the box.

Basically, he behaves like a border, but is sketched on the top of the box, without looking at the size of the box.

Conclusion

During this article, you have seen how to use padding, borders and outlines in CSS.

Источник

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