Kурс по уеб програмиране (2014)
Занятие №2: CSS
--
Въведение в CSS
Селектор, свойство, стойност
Идентификация и групиране на селектори
Цветове и фон
Форматиране на текст, списъци, таблици
CSS Box Model
Border, margin, padding
Позициониране на елементи
Псевдокласове и псевдоелементи
2. Съдържание
• Въведение в CSS
• Селектор, свойство, стойност
• Идентификация и групиране на селектори
• Цветове и фон
• Форматиране на текст, списъци, таблици
• CSS Box Model
• Border, margin, padding
• Позициониране на елементи
• Псевдокласове и псевдоелементи
3. Въведение в CSS
• Cascading Style Sheets
• Език, който съдържа множество инструменти за стилизиране
(инструктира как да се покаже) на HTML
• Разделя съдържанието на страницата от нейната презентация
• Дефинира шрифт, размер, широчина, фон....
• Подобрява потребителското изживяване в сайта
• Може да определя различна презентация за различен тип медиа –
screen, print, tv... дори braille
• Всеки браузър има свой-собствен, зададен по подразбиране стилов
лист
4. Въведение в CSS
• Използване на едно и също съдържание с различни стилове за
различни цели
• Външните стилови полета спестяват много работа
• Значително намаля количеството код в страницата
• Каскадни, защото децата наследяват родителите
• Връзката между HTML и CSS става по 3 основни начина
– Вградени в <head> елемента на HTML
<head>
<style>
h1 {
text-align: center;
color: red;
}
</style>
</head>
5. Въведение в CSS
• Връзката между HTML и CSS става по 3 основни начина
– Inline – Стил в самия HTML елемент
<h1 style="font-size:18px">Page title</h1>
– Външни – различни страници използват един и същ стил
• link
<link href=“mycss.css" rel="stylesheet" type="text/css"/>
• Import -
<style type="text/css">
@import "styles.css";
</style>
– Някои по-стари браузъри не разпознават import
– Проблеми с Internet Explorer
6. Въведение в CSS
• IE 6-9
– A sheet may contain up to 4095 rules
– A sheet may @import up to 31 sheets
– @import nesting supports up to 4 levels deep
• IE 10
– A sheet may contain up to 65534 rules
– A document may use up to 4095 stylesheets
– @import nesting is limited to 4095 levels (due to the 4095 stylesheet limit)
7. Селектор, свойство, стойност
• Селекторът е връзката между HTML документа и стиловия
лист и всички типове елементи в HTML са възможни
селектори – p, div, nav, span, input…
селектори {
свойство: стойност;
свойство: стойност;
свойство: стойност;
}
8. Селектор, свойство, стойност
• CSS селекторите се използват да намерят HTML елементите
базирани на тяхно id, classes, тип, атрибут, стойност и тн..
• Element селектор– прилага стил на HTML елемент/и
strong {
color: blue;
}
• Class селектор – прилага стил на елемент/и в HTML със
специфичен class атрибут
.myclass {
color: blue;
}
<h1 class="myclass">Заглавие</h1>
9. Селектор, свойство, стойност
• ID селектор– прилага стил на HTML елемент/и със
специфичен ID атрибут
#myid {
color: blue;
}
<h1 id="myid">Заглавие</h1>
10. Идентификация и групиране на селектори
• Възможно е да има много елементи с един с един и същ
стил
• Групирането на елементи намалява кода и значително
подобрява поддръжката от страна на разработчиците
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p {
text-align: center;
color: red;
}
11. Идентификация и групиране на селектори
• Възможно е да има много елементи с един с един и същ
стил
• Групирането на елементи намалява кода и значително
подобрява поддръжката от страна на разработчиците.
h1, h2, p {
text-align: center;
color: red;
}
12. Идентификация и групиране на селектори
• Комбиниране
#navigation p strong {
color: red;
}
<div id="navigation">
<h1 style="font-size:18px">Page title</h1>
<p>
Lorem Ipsum is <strong>simply dummy text</strong> of the prin
</p>
</div>
13. Идентификация и групиране на селектори
• Вложени селектори
nav p strong {
color: red;
}
<nav>
<h1 style="font-size:18px">Page title</h1>
<p>
Lorem Ipsum is <strong>simply dummy text</strong> of the prin
</p>
</nav>
14. Идентификация и групиране на селектори
• Атрибутни селектори
– Избира/селектира елементи по техните атрибути
a[title] {
color: red;
text-decoration: none;
}
<p>Lorem Ipsum is <a href="#" title="page title">simply dummy text</a> of the print</p>
<p>Lorem Ipsum is <a href="#">simply dummy text</a> of the print</p>
15. Идентификация и групиране на селектори
• Атрибутни селектори
– Избира/селектира елементи по стойността на техните
атрибути
input[type=text] {
color: red;
text-decoration: none;
}
<p>Lorem Ipsum is <a href="#" title="page title">simply dummy text</a> of the print</p>
<p>Lorem Ipsum is <a href="#">simply dummy text</a> of the print</p>
16. Идентификация и групиране на селектори
• Атрибутни селектори
– Избира/селектира елементи, чиито атрибутни стойности
съдържат определена дума
a[title*=someword] {
color: gray;
}
<p>Lorem Ipsum is <a href="#" title="someword in title">simply dummy text</a> of the print</p>
<p>Lorem Ipsum is <a href="#" title="other title">simply dummy text</a> of the print</p>
17. Идентификация и групиране на селектори
• Избиране/селектиране на всички елементи в даден
елемент
body * {
font-size: 10px;
}
<p>Lorem Ipsum is <a href="#" title="someword in title">simply dummy text</a> of the print</p>
<p>Lorem Ipsum is <a href="#" title="other title">simply dummy text</a> of the print</p>
18. Идентификация и групиране на селектори
• Селектиране на всички елементи с определен клас в даден
елемент
p > .otherclass {
color: green;
}
19. Форматиране
• Мерни единици
% percentage
in inch
cm centimeter
mm millimeter
em 1em is equal to the current font size. 2em means 2 times the size of the current font. E.g., if an element is displayed with a font of 12 pt,
then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can adapt automatically to the font that the reader uses
ex one ex is the x-height of a font (x-height is usually about half the font-size)
pt point (1 pt is the same as 1/72 inch)
pc pica (1 pc is the same as 12 points)
px pixels (a dot on the computer screen)
20. Форматиране
• Цветове
Hex стойностите представляват три двойки двуцифрени шестнадесетични числа
започващи със символа ‘#’.
Color Color HEX Color RGB
#000000 rgb(0,0,0)
#FF0000 rgb(255,0,0)
#00FF00 rgb(0,255,0)
#0000FF rgb(0,0,255)
#FFFF00 rgb(255,255,0)
#00FFFF rgb(0,255,255)
#FF00FF rgb(255,0,255)
#C0C0C0 rgb(192,192,192)
#FFFFFF rgb(255,255,255)
21. Форматиране
• Добавяне на фон
Property Description
background Sets all the background properties in one declaration
background-attachment Sets whether a background image is fixed or scrolls with the rest of
the page
background-color Sets the background color of an element
background-image Sets the background image for an element
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated
22. Форматиране
• Добавяне на фон
body {
background-image: url('css/red001.jpg');
background-color: #f4f4f4;
background-repeat: no-repeat;
background-position: center bottom;
background-attachment: scroll;
background-size: cover;
}
23. Форматиране на текст
• Поддържа правила за стилизиране на:
– Шрифт
font-family: Verdana, Geneva, sans-serif;
font-size: 10px;
font-style: italic;
– Цвят
color: #930;
opacity: 0.6;
– Оформление
text-decoration: line-through;
text-transform: uppercase;
letter-spacing: 20px;
text-align: center;
– http://www.w3schools.com/cssref/default.asp
26. Форматиране на таблици
• Форматиране на таблица
table {
width: 500px;
border-collapse: collapse;
}
• Атрибутът border-collapse определя вида на рамката
table, td, th {
border: 1px solid green;
}
th {
background-color: green;
color: white;
}
27. CSS Box Model
• CSS box model представя всеки елемент като съвкупност от
четири вложени полета
28. CSS Box Model
• Описание на различните полета:
– Margin - Изчиства полето около border. Margin няма цвят на
фона и е прозрачен
– Border - Поле, което обикаля около padding и съдържание.
– Padding - Изчиства полето около съдържанието. Padding се
влияе от фона на кутията.
– Съдържание - съдържанието на кутията, където се показва
текст и картинки
29. CSS Box Model
• За да задавате правилни ширина и височина на
елементите, трябва да знаете как работи box моделът
.math {
width: 250px;
padding: 10px;
border: 5px solid gray;
margin: 10px;
}
• Калкулиране на ширината и височината на елементите в
CSS Box Model
Обща ширина = ширина на съдържанието + ляв padding + десен padding + ляв border +
десен border + ляв margin + десен margin
Обща височина = височината на съдържанието + горен padding + долен padding + горен
border + долен border + горен margin + долен margin
250px (width) + 20px (left + right padding) + 10px (left + right border)
+ 20px (left + right margin) = 300px
30. Border, margin, padding
• Border - рамка
Property Description
border Sets all the border properties in one declaration
border-bottom Sets all the bottom border properties in one declaration
border-bottom-color Sets the color of the bottom border
border-bottom-style Sets the style of the bottom border
border-bottom-width Sets the width of the bottom border
border-color Sets the color of the four borders
border-left Sets all the left border properties in one declaration
border-left-color Sets the color of the left border
border-left-style Sets the style of the left border
border-left-width Sets the width of the left border
border-right Sets all the right border properties in one declaration
border-right-color Sets the color of the right border
border-right-style Sets the style of the right border
border-right-width Sets the width of the right border
border-style Sets the style of the four borders
border-top Sets all the top border properties in one declaration
border-top-color Sets the color of the top border
border-top-style Sets the style of the top border
border-top-width Sets the width of the top border
border-width Sets the width of the four borders
31. Border, margin, padding
• Margin
Property Description
margin A shorthand property for setting the margin properties in one declaration
margin-bottom Sets the bottom margin of an element
margin-left Sets the left margin of an element
margin-right Sets the right margin of an element
margin-top Sets the top margin of an element
32. Border, margin, padding
• Padding
Property Description
padding A shorthand property for setting all the padding properties in one
declaration
padding-bottom Sets the bottom padding of an element
padding-left Sets the left padding of an element
padding-right Sets the right padding of an element
padding-top Sets the top padding of an element
33. Позициониране на елементи
• Position
Value Description
static Default value. Elements render in order, as they appear in the document
flow
absolute The element is positioned relative to its first positioned (not static)
ancestor element
fixed The element is positioned relative to the browser window
relative The element is positioned relative to its normal position, so "left:20" adds
20 pixels to the element's LEFT position
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit
34. Позициониране на елементи
• Свойството float – указва на елемент да се позиционира в
ляво или в дясно, позволявайки на другите елементи да
„плават“ около него
.left {
float: left;
color: blue;
width: 300px;
}
.right {
float: right;
color: red;
width: 300px;
}
• Изчистването на плаващите елементи става с clear
– Стойности на свойството clear: both, left и right
35. Позициониране на елементи
• Свойствата display и visibility
– display – определя как даден елемент да бъде представен
– visibility – определя дали даден елемент да се вижда или не
– Разликата между двата е значителна!
.hidden {
visibility: hidden;
}
.displayhidden {
display: none;
}
36. Позициониране на елементи
• Свойството display
– block – съдържа padding, border, margin
– inline – игнорира height и width
– inline-block – добавя height и width
• Свойството overflow
– указва какво ще се случи при препълване на съдържанието
– примери: http://css-tricks.com/examples/OverflowExample/
• Свойството z-index
– указва как да се подредят елементите по оста Z
37. Псевдокласове и псевдоелементи
• Псевдокласове и псевдоелементи
– Използват се да добавят ефект към някои от селекторите
a:hover {
color: #ff00ff;
}
– Псевдокласове и CSS класове
a.blue:hover {
color: blue;
}
38. Псевдокласове и псевдоелементи
• Псевдокласове и псевдоелементи
p:first-child i {
color: blue;
}
a::before {
content: "-";
color: green;
}
a::after{
content: "-";
}
39. Псевдокласове и псевдоелементи
• Псевдокласове и псевдоелементи
Selector Example Example description
:link a:link Selects all unvisited links
:visited a:visited Selects all visited links
:active a:active Selects the active link
:hover a:hover Selects links on mouse over
:focus input:focus Selects the input element which has focus
::first-letter p::first-letter Selects the first letter of every <p> element
::first-line p::first-line Selects the first line of every <p> element
:first-child p:first-child Selects every <p> elements that is the first child of its parent
::before p::before Insert content before every <p> element
::after p::after Insert content after every <p> element
:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it"