§ 8. Создание списков в HTML
В HTML списки создаются с помощью тегов и . В первом случае создается упорядоченный (нумерованный), во втором неупорядоченный (маркированный) списки. Каждый элемент списка выделяется тегом . Браузер отображает элементы списка с новой строки в виде столбца с отступом и маркерами. Вид маркера определяется атрибутом type.
В нумерованном списке маркеры (значения атрибута type) такие:
- 1 — нумерация арабскими цифрами (по умолчанию);
- A — большими латинскими буквами по алфавиту;
- a — маленькими латинскими буквами;
- I — большими римскими цифрами;
- i — маленькими римскими цифрами.
Например, HTML-код
Первый элемент.Второй элемент.Третий элемент.
браузер покажет так:
- Первый элемент.
- Второй элемент.
- Третий элемент.
В маркированном списке значения атрибута type такие:
- disc — закрашенный кружок (по-умолчанию);
- circle — незакрашенный кружок;
- square — закрашенный квадратик.
Например, HTML-код
Первый элемент.Второй элемент.Третий элемент.
в браузере выглядит так:
- Первый элемент.
- Второй элемент.
- Третий элемент.
Как и остальные теги HTML, списки можно вкладывать друг в друга. Получаются многоуровневые вложенные списки. Например, код:
Первый элемент. Второй элемент. Третий элемент. Четвёртый элемент. Пятый элемент.
браузер покажет так:
- Первый элемент.
-
- Второй элемент.
- Третий элемент.
- Четвёртый элемент.
- Пятый элемент.
Floating Images Right to Wrap Text
The following code floats an image to the right. Notice that the margin differs from the code used when an image is floating to the left.
Pellentesque mattis tincidunt porttitor. Maecenas condimentum iaculis ligula, sit amet scelerisque nibh aliquam in. Quisque ornare gravida est ut fermentum. Nam venenatis pretium enim, in laoreet nibh tristique sit amet.
Nullam cursus varius tellus, id laoreet magna hendrerit at. Nulla sit amet purus at nunc blandit ultricies eu a urna. Proin euismod porttitor neque id ultricies. Aenean sed turpis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec sem eros, ornare ut, commodo eu, tempor nec, risus. Donec laoreet dapibus ligula. Praesent orci leo, bibendum nec, ornare et, nonummy in, elit. Donec interdum feugiat leo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque feugiat ullamcorper ipsum.
§ 6. Заголовки
Для задания названий разделов и подразделов в HTML используются теги заголовков. Существуют шесть уровней заголовков и обозначаются они так:
- — заголовок первого уровня
- — заголовок второго уровня
- — заголовок третьего уровня
- — заголовок четвёртого уровня
- — заголовок пятого уровня
- — заголовок шестого уровня
Заголовки выделяются полужирным шрифтом и отделяются от остального текста пустой строкой. Самый крупный заголовок (им выделено название этого урока), а самый маленький . Теги заголовков имеют атрибуты:
- align — выравнивание текста заголовка на странице (значения те же, что и для выравнивания обычного текста);
- title — всплывающая подсказка, которая появляется при наведении мыши на заголовок.
Например, код HTML:
align=»center» title=»Всплывающая подсказка. Чтобы увидеть, наведи мышь на заголовок.»>Заголовок 4 уровня
в браузере будет выглядеть так:
When justify-content Or align-content Do Not Work
The and properties in Grid and Flexbox are about distributing extra space. So the thing to check is that you have extra space.
Here is a Flex example: I have set and I have three items. They don’t take up all of the space in the flex container, so I have spare space on the main axis, the initial value for is and so my items all line up at the start and the extra space is at the end. I am using the Firefox Flex Inspector to highlight the space.
If I change flex-direction to , that extra space is now distributed between the items:
If I now add more content to my items so they become larger and there is no longer any additional space, then does nothing — simply because there is no space to distribute.
A common question I’m asked is why isn’t working when is . This is generally because there is no space to distribute. If you take the above example and make it , the items will display as a column, but there will be no additional space below the items as there is when you do . This is because when you make a Flex Container with you have a block level flex container; this will take up all possible space in the inline direction. In CSS, things do not stretch in the block direction, so no extra space.
Add a height to the container and — as long as that is more than is required to display the items — you have extra space and therefore will work on your column.
The Two Types Of Alignment
When aligning flex and grid items, you have two possible things to align:
- You have the spare space in the grid or flex container (once the items or tracks have been laid out).
- You also have the item itself inside the grid area you placed it in, or on the cross axis inside the flex container.
I showed you a set of properties above, and the alignment properties can be thought of as two groups. Those which deal with distribution of spare space, and those which align the item itself.
Dealing With Spare Space: And
The properties which end in are about space distribution, so when you choose to use or you are distributing available space between grid tracks or flex items. They don’t change the size of the flex or grid items themselves; they move them around because they change where the spare space goes.
Below, I have a flex example and a grid example. Both have a container which is larger than required to display the flex items or grid tracks, so I can use and to distribute that space.
See the Pen justify-content and align-content by Rachel Andrew.
See the Pen justify-content and align-content by Rachel Andrew.
Moving Items Around: , , And
We then have and as applied to individual flex or grid items; you can also use and on the container to set all the properties at once. These properties deal with the actual flex or grid item, i.e. moving the content around inside the Grid Area or flex line.
- Grid LayoutYou get both properties as you can shift the item on the block and inline axis as we have a defined Grid Area in which it sits.
- Flex LayoutYou can only align on the cross axis as the main axis is controlled by space distribution alone. So if your items are a row, you can use to shift them up and down inside the flex line, aligning them against each other.
In my example below, I have a flex and a grid container, and am using and in Flexbox to move the items up and down against each other on the cross axis. If you use Firefox, and inspect the element using the Firefox Flexbox Inspector, you can see the size of the flex container and how the items are being moved vertically inside of that.
In grid, I can use all four properties to move the items around inside their grid area. Once again, the Firefox DevTools Grid Inspector will be useful when playing with alignment. With the grid lines overlaid, you can see the area inside which the content is being moved:
Play around with the values in the CodePen demo to see how you can shift content around in each layout method:
See the Pen justify-self, align-self, justify-items, align-items by Rachel Andrew.
See the Pen justify-self, align-self, justify-items, align-items by Rachel Andrew.
§ 1. Теория
Здесь нужно коротко упомянуть о том, что такое текст в «электронном» виде. Я не буду подробно вдаваться в то, как он представляется в различных кодировках и системах. Скажу лишь о том, как связаны форматирование текста в HTML и его редактирование в текстовых редакторах.
Допустим, ты набрал текст в редакторе, произвел его форматирование (выделил какие-то слова жирным или курсивом), либо сделал с ним что-то ещё. Затем скопировал и вставил текст в свой html-код. Открываешь html-страницу в браузере, а всё твоё форматирование куда-то исчезло. Происходит это потому, что текстовый редактор для форматирования текста применяет свои спецсимволы (по сути те же теги, только используются в текстовых редакторах), которые ты по умолчанию не видишь.
В окне редактора ты видишь только текст. А на самом деле там есть ещё управляющие спецсимволы, с помощью которых редактор «понимает», как ему отображать тот или иной кусок текста. Т. е., повторюсь, это то же самое, что и теги в HTML, только «заточенные» под использование в текстовых редакторах.
Но, не смотря на это, существует способ перенести текст из редактора и вставить его в html-код в исходном виде. И раз уж об этом зашла речь, то форматирование текста и начнем изучать с этого тега. Итак, приступим.
Flexbox And Micro-Components
One of the things I think is often overlooked is how useful Flexbox is for doing tiny layout jobs, where you might think that using is the way to go. I often use Flexbox to get neat alignment of small patterns; for example, aligning an icon next to text, baseline aligning two things with different font sizes, or making form fields and buttons line up properly. If you are struggling to get something to line up nicely with , then perhaps try doing the job with Flexbox. Remember that you can also create an inline flex container if you want with .
See the Pen inline-flex example by Rachel Andrew.
See the Pen inline-flex example by Rachel Andrew.
There is no reason not to use Flexbox, or even Grid for tiny layout jobs. They aren’t just for big chunks of layout. Try the different things available to you, and see what works best.
People are often very keen to know what the right or wrong way to do things is. In reality, there often is no right or wrong; a small difference in your pattern might mean the difference between Flexbox working best, where otherwise you would use .
Floating Images Left Horizontally
This will use the same code as before (See below). The images are simply placed one after another to get them to float horizontally. Floating images in line with each other is another way to display your images as a gallery.
Nullam cursus varius tellus, id laoreet magna hendrerit at. Nulla sit amet purus at nunc blandit ultricies eu a urna. Proin euismod porttitor neque id ultricies. Aenean sed turpis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec sem eros, ornare ut, commodo eu, tempor nec, risus. Donec laoreet dapibus ligula.
This concludes how to align and float images with CSS. Use these options to help create more informative and creative content by blending your text and images on your web pages.
Join our community to receive specialized help with HTML and design, special hosting offers, and more! The next tutorial will show you how to make a simple CSS Drop Down Menu. We also have a helpful article on External, Internal, and Inline CSS styles.
Looking for more help with CSS? Check out our introduction to CSS guide!
HTML References
HTML by AlphabetHTML by CategoryHTML Browser SupportHTML AttributesHTML Global AttributesHTML EventsHTML ColorsHTML CanvasHTML Audio/VideoHTML Character SetsHTML DoctypesHTML URL EncodeHTML Language CodesHTML Country CodesHTTP MessagesHTTP MethodsPX to EM ConverterKeyboard Shortcuts
HTML Tags
<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>
Definition and Usage
The tag is used to embed an image in an HTML page.
Images are not technically inserted into a web page; images
are linked to web pages. The tag creates a holding space for the referenced image.
The tag has two required attributes:
- src — Specifies the path to the image
- alt — Specifies an alternate text for the image, if the image for some
reason cannot be displayed
Note: Also, always specify the width and height of an image.
If width and height are not specified, the page might flicker while the image
loads.
Tip: To link an image to another document, simply nest the tag inside
an <a> tag (see example below).
More Examples
Example
Align image (with CSS):
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″ style=»vertical-align:bottom»>
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″ style=»vertical-align:middle»>
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″ style=»vertical-align:top»>
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″ style=»float:right»>
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″ style=»float:left»>
Example
Add image border (with CSS):
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″
style=»border:5px solid black»>
Example
Add left and right margins to image (with CSS):
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″
style=»vertical-align:middle;margin:0px 50px»>
Example
Add top and bottom margins to image (with CSS):
<img src=»smiley.gif» alt=»Smiley face» width=»42″ height=»42″ style=»vertical-align:middle;margin:50px 0px»>
Example
How to insert images from another folder or from another web site:
<img src=»/images/stickman.gif» alt=»Stickman» width=»24″ height=»39″>
<img src=»https://www.w3schools.com/images/lamp.jpg» alt=»Lamp» width=»32″
height=»32″>
Example
How to add a hyperlink to an image:
<a href=»https://www.w3schools.com»><img src=»w3html.gif»
alt=»W3Schools.com» width=»100″ height=»132″></a>
Example
How to create an image map, with clickable regions. Each region is a hyperlink:
<img src=»workplace.jpg» alt=»Workplace» usemap=»#workmap» width=»400″
height=»379″><map name=»workmap»> <area shape=»rect»
coords=»34,44,270,350″ alt=»Computer» href=»computer.htm»> <area
shape=»rect» coords=»290,172,333,250″ alt=»Phone» href=»phone.htm»>
<area shape=»circle» coords=»337,300,44″ alt=»Cup of coffee» href=»coffee.htm»>
</map>
§ 5. Перенос строки и горизонтальная черта
Если нужно обеспечить переход на новую строку без вставки пустой строки (это происходит, когда ты в текстовом редакторе нажимаешь Enter), то используется тег . Например, html-код
1. Первая строка. 2. Вторая строка.
в браузере будет выглядеть так:
1. Первая строка. 2. Вторая строка.
У нет закрывающего тега. Ты уже наверное догадался, что для вставки нескольких пустых строк, нужно записать тег несколько раз подряд.
Визуально разделить части текста можно ещё при помощи тега . Этот тег создает на странице разделительную полосу (например, как зелёная в начале этой статьи). Тег имеет следующие атрибуты:
- size — толщина полосы;
- width — ширина полосы;
- align — выравнивание;
- color — цвет полосы;
- noshade — атрибут, не имеющий значений. Если указан, то создается сплошная чёрная полоса без тени.
Например, html-код:
align=»center» size=»5″ width=»50%» color=»#3399ff»>
в браузере примет вид
Ширину и толщину можно указывать как в пикселах (тогда величина будет постоянной), так и в процентах (тогда величина будет меняться в зависимости от разрешения экрана).
Aligning Text And Inline Elements
When we have some text and other inline elements on a page, each line of content is treated as a line box. The property will align that content on the page, for example, if you want your text centered, or justified. Sometimes, however, you may want to align things inside that line box against other things, for example, if you have an icon displayed alongside text, or text of different sizes.
In the example below, I have some text with a larger inline image. I am using on the image to align the text to the middle of the image.
See the Pen Vertical Alignment example by Rachel Andrew.
See the Pen Vertical Alignment example by Rachel Andrew.
The Property And Alignment
Remember that the property will change the size of the line-box and therefore can change your alignment. The following example uses a large line-height value of 150px, and I have aligned the image to . The image is aligned to the top of the line box and not the top of the text, remove that line-height or make it less than the size of the image and the image and text will line up at the top of the text.
See the Pen Vertical Alignment and line-height by Rachel Andrew.
See the Pen Vertical Alignment and line-height by Rachel Andrew.
It turns out that and indeed the size of text is pretty complicated, and I’m not going to head down that rabbit hole in this article. If you are trying to precisely align inline elements and want to really understand what is going on, I recommend reading “Deep Dive CSS: Font Metrics, And .”
When Can I Use The Property?
The property is useful if you are aligning any inline element. This includes elements with . The content of table cells can also be aligned with the property.
The property has no effect on flex or grid items, and therefore if used as part of a fallback strategy, will cease to apply the minute the parent element is turned into a grid or flex Container. For example, in the next pen, I have a set of items laid out with and this means that I get the ability to align the items even if the browser does not have Flexbox:
See the Pen inline-block and vertical-align by Rachel Andrew.
See the Pen inline-block and vertical-align by Rachel Andrew.
In this next pen, I have treated the as a fallback for Flex layout. The alignment properties no longer apply, and I can add to align the items in Flexbox. You can tell that the Flexbox method is in play because the gap between items that you will get when using is gone.
See the Pen inline-block flex fallback by Rachel Andrew.
See the Pen inline-block flex fallback by Rachel Andrew.
The fact that works on table cells is the reason that the trick to vertically center an item using works.
Now that we do have better ways to align boxes in CSS (as we will look at in the next section), we don’t need to employ the and properties in places other than the inline and text elements for which they were designed. However, they are still completely valid to use in those text and inline formats, and so remember if you are trying to align something inline, it is these properties and not the Box Alignment ones that you need to reach for.
Box Alignment
The Box Alignment Specification deals with how we align everything else. The specification details the following alignment properties:
You might already think of these properties as being part of the Flexbox Specification, or perhaps Grid. The history of the properties is that they originated as part of Flexbox, and still exist in the Level 1 specification; however, they were moved into their own specification when it became apparent that they were more generally useful. We now also use them in Grid Layout, and they are specified for other layout methods too, although current browser support means that you won’t be able to use them just yet.
Therefore, next time someone on the Internet tells you that vertical alignment is the hardest part of CSS, you can tell them this (which even fits into a tweet):
In the future, we may even be able to dispense with , once the Box Alignment properties are implemented for Block Layout. At the moment, however, making the parent of the thing you want centering a flex container is the way to get alignment horizontally and vertically.
§ 4. Выравнивание текста
Для того, чтобы выровнять текст используется атрибут align с возможными значениями center, left, right и justify. Он, соответственно, выравнивает текст по центру, по левому краю, по правому краю и одновременно по двум краям сразу. Например, html-код:
align=»center»>Текст по центру
выровняет текст по центру:
Текст по центру
А этот код:
right»>Выравнивание текста по правому краю
выровняет текст по правому краю
Выравнивание текста по правому краю
Если атрибут align не используется, то текст будет выровнен по левому краю. Это происходит по умолчанию. Пример, код:
По умолчанию текст выравнивается по левому краю
выровнит текст по левому краю
По умолчанию текст выравнивается по левому краю
Floating Images Using CSS
Floating images allow images to align horizontally with each other and allow text to wrap around the image. The following will explain horizontally aligning images and floating images around the text.
Floating Images Left to Wrap Text
This code aligns an image to the left of a text block. Note that the margin in the code determines the space around the image. The code defines the space in pixels going clockwise: top, right, bottom, and left.
You can see that the code below has a margin of 0px (top), 15px (right), 15px (bottom), and 0 px (left). The code allows for 15 pixels of space to the top and right of the image.
Nunc pulvinar lacus id purus ultrices id sagittis neque convallis. Nunc vel libero orci. Vivamus at dolor a nibh aliquet luctus. Duis imperdiet mi id lorem pellentesque tempus. Ut quis felis posuere tellus feugiat ultrices. Praesent id tortor non tellus viverra placerat.Nullam cursus varius tellus, id laoreet magna hendrerit at. Nulla sit amet purus at nunc blandit ultricies eu a urna. Proin euismod porttitor neque id ultricies. Proin faucibus convallis elit. Maecenas rhoncus arcu at arcu. Proin libero. Proin adipiscing. In quis lorem vitae elit consectetuer pretium. Nullam ligula urna, adipiscing nec, iaculis ut, elementum non, turpis. Fusce pulvinar.
Important! Floated images will overlap each other if the float is not cleared. Ensure you place a clear float code after each section your image is floating in. Below is the code to clear your floats.
Why Is There No justify-self In Flexbox?
Grid Layout implements all of the properties for both axes because we always have two axes to deal with in Grid Layout. We create tracks (which may leave additional space in the grid container in either dimension,) and so we can distribute that space with or . We also have Grid Areas, and the element in that area may not take up the full space of the area, so we can use or to move the content around the area (or , to change the alignment of all items).
Flexbox does not have tracks in the way that Grid layout does. On the main axis, all we have to play with is the distribution of space between the items. There is no concept of a track into which a flex item is placed. So there is no area created in which to move the item around in. This is why there is no property on the main axes in Flexbox.
Sometimes, however, you do want to be able to align one item or part of the group of items in a different way. A common pattern would be a split navigation bar with one item being separated out from the group. In that situation, the specification advises the use of auto margins.
An auto margin will take up all of the space in the direction it is applied, which is why we can center a block (such as our main page layout) using a left and right margin of auto. With an auto margin on both sides, each margin tries to take up all the space and so pushes the block into the middle. With our row of flex items, we can add to the item we want the split to happen on, and as long as there is available space in the flex container, you get a split. This plays nicely with Flexbox because as soon as there is no available space, the items behave as regular flex items do.
See the Pen Alignment with auto margins by Rachel Andrew.
See the Pen Alignment with auto margins by Rachel Andrew.
15.2 Fonts
The following HTML elements specify font information. Although they are
not all , their use is
discouraged in favor of style sheets.
15.2.1 Font style elements:
the TT, I, B,
BIG,
SMALL,
STRIKE, S, and U elements
<!ENTITY % fontstyle " | | | | "> <!ELEMENT (|) - - ()*> <!ATTLIST (|) -- , , -- >
Start tag: required, End tag:
required
Attributes defined elsewhere
- , ()
- (), ()
- ()
- ()
- , , , , , , , , ()
Rendering of font style elements depends on the user agent. The following is
an informative description only.
- TT: Renders as teletype or monospaced text.
- I: Renders as italic text style.
- B: Renders as bold text style.
- BIG: Renders text in a «large» font.
- SMALL: Renders text in a «small» font.
- STRIKE and S: Render strike-through style text.
- U: Renders underlined text.
The following sentence shows several types of text:
<P><b>bold</b>, <i>italic</i>, <b><i>bold italic</i></b>, <tt>teletype text</tt>, and <big>big</big> and <small>small</small> text.
These words might be rendered as follows:
It is possible to achieve a much richer variety of font effects using style
sheets. To specify blue, italic text in a paragraph with CSS:
<HEAD> <STYLE type="text/css"> P#mypar {font-style: italic; color: blue} </STYLE> </HEAD> <P id="mypar">...Lots of blue italic text...
Font style elements must be properly nested. Rendering of nested font style
elements depends on the user agent.
15.2.2 Font modifier
elements: FONT and BASEFONT
and are .
See the for
the formal definition.
Attribute definitions
- size =
-
This
attribute sets the size of the font. Possible values:- An integer between 1 and 7. This sets the font to some fixed size, whose
rendering depends on the user agent. Not all user agents may render all seven
sizes. - A relative increase in font size. The value «+1» means one size larger. The
value «-3» means three sizes smaller. All sizes belong to the scale of 1 to
7.
- An integer between 1 and 7. This sets the font to some fixed size, whose
- color =
-
This
attribute sets the text color. - face =
-
This
attribute defines a comma-separated list of font names the user agent should
search for in order of preference.
Attributes defined elsewhere
- , ()
- (), ()
- ()
- ()
The element changes the font size and color for text in its
contents.
The element sets the base font size (using the size attribute). Font size changes achieved with
are relative to the base font size set by . If is not used, the default base font size is 3.
DEPRECATED EXAMPLE:
The following example will show the difference between the seven font sizes
available with :
<P><font size=1>size=1</font> <font size=2>size=2</font> <font size=3>size=3</font> <font size=4>size=4</font> <font size=5>size=5</font> <font size=6>size=6</font> <font size=7>size=7</font>
This might be rendered as:
The following shows an example of the effect of relative font sizes using a
base font size of 3:
The base font size does not apply to headings, except where these are
modified using the element with a relative font size change.
Attributes
Attribute | Value | Description |
---|---|---|
alt | text | Specifies an alternate text for an image |
crossorigin | anonymous use-credentials |
Allow images from third-party sites that allow cross-origin access to be used with canvas |
height | pixels | Specifies the height of an image |
ismap | ismap | Specifies an image as a server-side image map |
eagerlazy | Specifies whether a browser should load an image immediately or to defer loading of images until some conditions are met |
|
longdesc | URL | Specifies a URL to a detailed description of an image |
referrerpolicy | no-referrerno-referrer-when-downgradeorigin origin-when-cross-originunsafe-url |
Specifies which referrer information to use when fetching an image |
sizes | sizes | Specifies image sizes for different page layouts |
src | URL | Specifies the path to the image |
srcset | URL-list | Specifies a list of image files to use in different situations |
usemap | #mapname | Specifies an image as a client-side image map |
width | pixels | Specifies the width of an image |
Wrapping Up
To wrap up, I have a quick summary of the basics of alignment. If you remember these few rules, you should be able to align most things with CSS:
- Are you aligning text or an inline element? If so, you need to use , , and .
- Do you have an item or items you want to align in the center of the page or container? If so, make the container a flex container then set and .
- For Grid Layouts, the properties that start with work in the Block direction; those which start with work in the inline direction.
- For Flex Layouts, the properties that start with work on the Cross Axis; those which start with work on the main axis.
- The and properties distribute extra space. If you have no extra space in your flex or grid container, they will do nothing.
- If you think you need in Flexbox, then using an auto margin will probably give you the pattern you are after.
- You can use Grid and Flexbox along with the alignment properties for tiny layout jobs as well as main components — experiment!
For more information about alignment, see these resources:
- CSS Box Alignment (MDN web docs)
- Everything You Need To Know About Alignment In Flexbox
- Box Alignment Cheatsheet
(il)