Содержание
예제
선택자
- 또는
- HTML 표의 홀수번째 행을 나타냅니다.
- 또는
- HTML 표의 짝수번째 행을 나타냅니다.
- 임의의 7번째 요소를 나타냅니다.
- 5 , 10 , 15 , … 번째의 요소를 나타냅니다. 패턴 공식을 만족하는 첫 번째 값은 으로서 아무 요소도 선택하지 않는데, 요소의 인덱스는 1부터 시작하지만 은 0부터 증가하기 때문입니다. 다소 의아할 수 있으나, 바로 아래 예제처럼 공식의 B 부분이 >0인 경우 보다 납득하기 쉬워집니다.
- 7번째와 그 이후의 모든 요소, 즉 7 , 8 , 9 , … 를 나타냅니다.
- 4 , 7 , 10 , 13 , … 번째의 요소를 나타냅니다.
- 앞에서 세 개의 요소를 나타냅니다.
- 형제 그룹 내의 모든 요소를 나타냅니다. 단순한 선택자와 동일하지만 더 높은 명시도를 가집니다.
- 또는
- 형제 그룹 내의 모든 첫 번째 요소를 나타냅니다. 선택자와 동일하며 같은 명시도를 가집니다.
- 형제 그룹 내에서 8번째부터 15번째 까지의 요소를 나타냅니다.
HTML
<h3><code>span:nth-child(2n+1)</code>, WITHOUT an <code><em></code> among the child elements.</h3> <p>Children 1, 3, 5, and 7 are selected.</p> <div class="first"> <span>Span 1!</span> <span>Span 2</span> <span>Span 3!</span> <span>Span 4</span> <span>Span 5!</span> <span>Span 6</span> <span>Span 7!</span> </div> <br> <h3><code>span:nth-child(2n+1)</code>, WITH an <code><em></code> among the child elements.</h3> <p>Children 1, 5, and 7 are selected.<br> 3 is used in the counting because it is a child, but it isn't selected because it isn't a <code><span></code>.</p> <div class="second"> <span>Span!</span> <span>Span</span> <em>This is an `em`.</em> <span>Span</span> <span>Span!</span> <span>Span</span> <span>Span!</span> <span>Span</span> </div> <br> <h3><code>span:nth-of-type(2n+1)</code>, WITH an <code><em></code> among the child elements.</h3> <p>Children 1, 4, 6, and 8 are selected.<br> 3 isn't used in the counting or selected because it is an <code><em></code>, not a <code><span></code>, and <code>nth-of-type</code> only selects children of that type. The <code><em></code> is completely skipped over and ignored.</p> <div class="third"> <span>Span!</span> <span>Span</span> <em>This is an `em`.</em> <span>Span!</span> <span>Span</span> <span>Span!</span> <span>Span</span> <span>Span!</span> </div>
CSS
html { font-family: sans-serif; } span, div em { padding: 5px; border: 1px solid green; display: inline-block; margin-bottom: 3px; } .first span:nth-child(2n+1), .second span:nth-child(2n+1), .third span:nth-of-type(2n+1) { background-color: lime; }
Модульная сетка (flexbox)
По умолчанию в сборку берётся файл с примесями, возвращающими правила модульной сетки. Cелекторов в CSS не добавляет, нужно писать семантические селекторы и вызывать примеси. Настройки по умолчанию вынесены в переменные ( и ).
- Любое кол-во колонок, в т.ч. разная колоночность на разных ширинах вьюпорта.
- Любые промежутки между колонками, в т.ч. разные на разных ширинах вьюпорта.
.promo { &__inner { @include container(); // это контейнер, padding по умолчанию (из переменной) } &__grid { @include row();// это прямой родитель сетки, margin по умолчанию (из переменной) } &__img { @include col(); // узкий вьюпорт, 100% ширина и padding по умолчанию @include col(md, 5); // MD-вьюпорт (786 по умолчанию) ширина 5 колонок и padding по умолчанию } &__text { @include col(); // узкий вьюпорт, 100% ширина и padding по умолчанию @include col(md, 7); // MD-вьюпорт (786 по умолчанию) ширина 7 колонок и padding по умолчанию } }
.row // Родитель. Указаны промежутки между ячейками: XS|SM|MD|LG|XL|XXL; @include row($grid-gutter-width, 10px, 12px, 16px, 20px, 26px); &__element { @include col(); // малые ширины — 12 из 12, промежутки по умолчанию @include col(sm, 6, $grid-columns, 10px); // SM (480 по умолчанию) — 6 из 12, промежутки 10px @include col(md, 4, $grid-columns, 12px); // MD (768 по умолчанию) — 4 из 12, промежутки 12px @include col(lg, 3, $grid-columns, 16px); // LG (992 по умолчанию) — 3 из 12, промежутки 16px @include col(xl, 2, $grid-columns, 20px); // XL (1200 по умолчанию) — 2 из 12, промежутки 20px @include col(xxl, 1, $grid-columns, 26px); // XXL (1800 по умолчанию) — 1 из 12, промежутки 26px } }
CSS Properties
align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function
backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside
caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor
direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight
grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows
hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing
line-height list-style list-style-image list-style-position list-style-type
margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode
object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y
padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes
resize right
scroll-behavior
tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top
transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function
unicode-bidi user-select
vertical-align visibility
white-space width word-break word-spacing word-wrap writing-mode
z-index
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function
backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside
caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor
direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight
grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows
hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing
line-height list-style list-style-image list-style-position list-style-type
margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode
object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y
padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes
resize right
scroll-behavior
tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top
transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function
unicode-bidi user-select
vertical-align visibility
white-space width word-break word-spacing word-wrap writing-mode
z-index
:nth-of-type
Похож на предыдущий псевдокласс, но учитывает тип элемента
Возьмем блок и разместим в него через один теги и. Для наглядности сделаем круглыми, а квадратными, а нумерацию не сквозную, а по тегам.
Для начала попробуем простые выражения для псевдокласса
и
В примере можно увидеть, что браузер считает только элементы указанного типа, а не все подряд как в случае с
See the Pen pozaJYr by Websitio (@Websitio) on CodePen.
Выберем нечетные и четные
See the Pen dybdoLE by Websitio (@Websitio) on CodePen.
Комбинированные :nth-of-type
Зададим фон нечетным только из первых 5ти
Зададим фон четным после 5го
See the Pen aboqOrR by Websitio (@Websitio) on CodePen.
Примеры
Примеры селекторов
- или
- Описывает нечётные строки HTML таблицы: 1, 3, 5, и т. д.
- or
- Описывает чётные строки HTML таблицы: 2, 4, 6, и т. д.
- Описывает седьмой элемент.
- Описывает элементы с номерами 5, 10, 15, и т. д.
- Описывает элементы с номерами 4, 7, 10, 13, и т. д.
- Описывает первые три элемента среди группы соседних элементов.
- Описывает каждый элемент среди группы соседних элементов. Эквивалентно простому селектору .
- или
- Описывает каждый элемент , являющийся первым среди группы соседних элементов. Эквивалентно селектору .
HTML
<h3><code>span:nth-child(2n+1)</code>, БЕЗ элемента <code><em></code> в группе элементов-потомков.</h3> <p>Элементы 1, 3, 5 и 7 будут выбраны.</p> <div class="first"> <span>Span 1!</span> <span>Span 2</span> <span>Span 3!</span> <span>Span 4</span> <span>Span 5!</span> <span>Span 6</span> <span>Span 7!</span> </div> <br> <h3><code>span:nth-child(2n+1)</code>, С элементом <code><em></code> в группе элементов-потомков.</h3> <p>Элементы 1, 5 и 7 будут выбраны.<br> 3 используется в подсчёте потому что это элемент-потомок, но он не выбран потому что он не <code><span></code>.</p> <div class="second"> <span>Span!</span> <span>Span</span> <em>Это `em`.</em> <span>Span</span> <span>Span!</span> <span>Span</span> <span>Span!</span> <span>Span</span> </div> <br> <h3><code>span:nth-of-type(2n+1)</code>, С элементом <code><em></code> в группе элементов-потомков.</h3> <p>Элементы 1, 4, 6 и 8 будут выбраны.<br> 3 не используется в подсчёте и не выбран, потому что это <code><em></code>, но не <code><span></code>, а <code>nth-of-type</code> выбирает только потомков этого типа. Элемент <code><em></code> полностью пропускается и игнорируется.</p> <div class="third"> <span>Span!</span> <span>Span</span> <em>Это `em`.</em> <span>Span!</span> <span>Span</span> <span>Span!</span> <span>Span</span> <span>Span!</span> </div>
CSS
html { font-family: sans-serif; } span, div em { padding: 5px; border: 1px solid green; display: inline-block; margin-bottom: 3px; } .first span:nth-child(2n+1), .second span:nth-child(2n+1), .third span:nth-of-type(2n+1) { background-color: lime; }
Фон и границы¶
- background
- background-attachment
- background-clip
- background-color
- background-image
- background-origin
- background-position
- background-position-x
- background-position-y
- background-repeat
- background-size
- border
- border-bottom
- border-bottom-color
- border-bottom-left-radius
- border-bottom-right-radius
- border-bottom-style
- border-bottom-width
- border-collapse
- border-color
- border-image
- border-image-outset
- border-image-repeat
- border-image-slice
- border-image-source
- border-image-width
- border-left
- border-left-color
- border-left-style
- border-left-width
- border-radius
- border-right
- border-right-color
- border-right-style
- border-right-width
- border-style
- border-top
- border-top-color
- border-top-left-radius
- border-top-right-radius
- border-top-style
- border-top-width
- border-width
- box-shadow
Блоки
Каждый блок лежит в в своей папке.
Возможное содержимое блока:
demo-block/ # Папка блока. bg-img/ # Изображения для использования в стилях (не обрабатываются автоматикой). img/ # Изображения, используемые этим блоком (копируются в папку сборки). demo-block.pug # Разметка (pug-примесь, отдающая разметку этого блока, описание API примеси). demo-block.scss # Стилевой файл этого блока (без стилей других блоков). demo-block.js # js-файл блока (без скриптов других блоков). readme.md # Описание для документации, подсказки.
Удобное создание нового блока
# формат: node createBlock.js ИМЯБЛОКА node createBlock.js demo-block # создаст папку блока, demo-block.scss, подпапки img/ и bg-img/ для этого блока node createBlock.js demo-block pug js # создаст папку блока, demo-block.scss, demo-block.pug, demo-block.js, подпапки img/ и bg-img/ для этого блока
Если блок уже существует, файлы не будут затёрты, но создадутся те файлы, которые ещё не существуют.
С этим читают