Html syntax for list

All HTML Tutorials

Before we begin, you may be wondering why navigation is included in an article about lists. As I said above, lists are used to build navigation menus — but why? The reason is because it is the globally accepted way to create navigation. This is means that it will help screen readers, web scanners and Google identify it as the navigation for your site. This is part of a thing called Search Engine Optimization (SEO), which I will go into in a later article.

In this article, I will start with what lists are and how to make them, then go into how they can be used to create navigation. Let’s get going!

Types of lists

There are three types of lists in HTML:

(see what I did there? I used a list 😜) Let’s go into what each one is for and how to code them…

Читайте также:  Java util concurrent runnable

Ordered lists

Ordered lists are lists with numbers, and look like so:

Here is the syntax for an ordered list:

ol> li>Itemli> li>Another itemli> li>A third itemli> ol> 

    tag stands for ordered list, and is the actual list element. Each item in the list is made using a
    element, which stands for list item.

Unordered lists

Unordered lists are very similar to ordered lists, except that they have bullet points instead of numbers:

The syntax for an unordered list is very similar to the syntax for an ordered list:

ul> li>Itemli> li>Another itemli> li>A third itemli> ul> 

    is replaced with
    (unordered list).

Definition lists

Definition lists are probably the least common list used in HTML, and also the most complicated. Definition lists are used sort of like you would find in a dictionary, with terms and definitions of those terms. Here is an example:

Ordered lists Lists with numbers Unordered lists Lists with bullet points Definition lists Lists used to define things

The syntax for definition lists is a bit more complicated, so I will explain first. First of all, a definition list is made using the tag, similar to ordered and unordered lists:

But what goes inside? Basically, a definition list is made up of term/definition pairs. The term and the definition each have their own element. The element for the definition term is , and the element for the definition description (definition of the term) is . Here is a simple term/definition pair in a list:

dl> dt>Termdt> dd>Definitiondd> dl> 

Using the information I’ve given you, try and work out what the code for the example list from above would be:

dl> dt>Ordered listsdt> dd>Lists with numbersdd> dt>Unordered listsdt> dd>Lists with bullet pointsdd> dt>Definition listsdt> dd>Lists used to define thingsdd> dl> 

There we go! Now you know all three types of lists in HTML!

What is navigation?

Navigation is the set of links that you click on to get to other parts of a site. For example, here is the navigation on my site:

My navigation bar with the Code The Web logo, a Home link and a Tags link

And here is an example from another site:

A navigation bar with a logo, links to pages, links to social media and a download now button

As I said earlier, navigation should be created with lists, for the purpose of Search Engine Optimization and general accessibility. Because the whole point of creating navigation with lists is for a global standard, there is a specific syntax that should be used to create them:

nav> ul> li>a href="/">Homea>li> li>a href="/about">Abouta>li> li>a href="/contact">Contacta>li> ul> nav> 

Basically, a navigation item should be created with the following structure:

Note that the ordered list is put in a element. This is the semantic tag for navigation on a page.

Try and create your own navigation with the following two items:

See if you got it right below:

nav> ul> li>a href="https://codetheweb.blog/">Homea>li> li>a href="https://codetheweb.blog/newsletter">Newslettera>li> ul> nav> 

Note that the default styling for the navigation code above looks really bad — in a later article, I will show you how to make a navigation bar that actually looks good, all while keeping the exact same HTML.

Conclusion

Woo! Now you know all three types of lists in HTML, as well as all about how to create navigation on a page.

If you enjoyed this article, don’t forget to share it so that more people will get to read it. As always, if you have any questions, feedback or just want to say hi then do so in the comments below. And if you want to stay up to date and have more awesome articles delivered to your inbox (once a week-ish), then don’t forget to subscribe to the newsletter.

Have fun, and I’ll see you all next week where I’ll be writing my first CSS tutorial.

P.S. — today is exactly one month since I wrote my first ever blog post!

Your FREE guide to learning HTML! 🎁

Источник

HTML Lists

HTML lists allow web developers to group a set of related items in lists.

Example

Unordered HTML List

    tag. Each list item starts with the
    tag.

The list items will be marked with bullets (small black circles) by default:

Example

Ordered HTML List

    tag. Each list item starts with the
    tag.

The list items will be marked with numbers by default:

Example

HTML Description Lists

HTML also supports description lists.

A description list is a list of terms, with a description of each term.

The tag defines the description list, the tag defines the term (name), and the tag describes each term:

Example

HTML List Tags

Tag Description
Defines an unordered list
Defines an ordered list
Defines a list item
Defines a description list
Defines a term in a description list
Describes the term in a description list

For a complete list of all available HTML tags, visit our HTML Tag Reference.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Списки в HTML: синтаксис и примеры использования

Подпишись на наш телеграм-канал TechRocks WEB-разработка?

Перевод статьи «HTML List – How to Use Bullet Points, Ordered, and Unordered Lists».

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

В общем, знать, как создаются списки, просто необходимо. Возможно, вы думаете, что это очень обыденная и заурядная тема, но она важна. Список — один из наиболее часто используемых компонентов в веб-разработке.

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

Как сделать список в HTML

Списки в HTML бывают упорядоченные и неупорядоченные.

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

Примером упорядоченного списка может служить нумерованный список. Он может начинаться с номера 1, затем будут идти номера 2, 3, 4 и так далее.

Но для упорядочивания элементов не обязательно используются числа. Могут быть и буквы: список начнется с буквы A, затем будут идти B, C, D и так далее.

Вот пример упорядоченного списка с именами студентов и их оценками:

Кроме упорядоченных списков в HTML есть и неупорядоченные. Пример — список задач. В представленном ниже TODO-списке мы видим, что я настолько увлечен программированием, что пожертвовал ради него завтраком.

Есть еще один вид списков — список определений (description list). Его мы рассмотрим чуть позже, а сейчас давайте разберем, как создавать каждый вид списков.

Как создать упорядоченный список

    (от ordered list — упорядоченный список).

    и закрывающим

      нам нужно определить элементы списка. Это делается при помощи тега
      .

    Вот полная HTML-структура упорядоченного списка:

    Итак, у нас есть список пронумерованных элементов. Нумерация начинается с 1, а далее инкрементируется до 2 и 3. Откройте этот CodePen и попробуйте поиграть с использованием ol-li .

    See the Pen Ordered List by Tapas Adhikary (@atapas) on CodePen.

    Виды упорядоченных списков в HTML

      атрибут type с нужным значением.

    Чтобы упорядочить список при помощи заглавных букв, нужно задать type значение A .

    Аналогично, можно указать в качестве значения для type строчную букву a : тогда для упорядочивания будут использоваться строчные буквы.

    Можно использовать римские цифры. Для этого задайте значение I для атрибута type .

    Попробуйте назначать свои значения для type в этом CodePen:

    See the Pen Ordered List Types by Tapas Adhikary (@atapas) on CodePen.

    Использование атрибута start в упорядоченных списках

      имеет интересный атрибут — start . С его помощью можно указать значение, с которого должна начаться нумерация списка.

    Допустим, мы хотим начать список не с 1, а с 30. Для этого нужно прописать значение 30 для атрибута start :

    Как создать неупорядоченный список

      (от unordered list — неупорядоченный список).

    Элементы списка при этом будут иметь маркировку по умолчанию — черные точки.

    Вот список моих любимых онлайн-ресурсов для изучения веб-программирования:

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

    Как сделать элементы списка ссылками

    Этот пример показывает, как добавить в наш предыдущий список ссылки на соответствующие сайты:

    Попробуйте сделать это самостоятельно:

    Виды неупорядоченных списков

    Как уже упоминалось, маркировку списков можно настраивать. Это делается при помощи CSS-свойства list-style .

    Для свойства list-style есть четыре основных значения:

    • none — перед элементами не будет вообще никаких значков
    • circle — значки будут в виде незаполненных кружков
    • disc — дефолтное значение, значки в виде черных точек
    • square — значки-квадратики

    Попробуйте поменять виды маркировки:

    А вы знали, что существуют еще и списки определений?

    В HTML есть еще один вид списков, но он используется не так уж часто. Это список определений. Определение — это небольшой текст о чем-либо (поясняющий что-либо).

    В списке определений у нас будут определяемые термины и их определения.

    Сам список создается при помощи тега .

    Внутри списка указываются термины (при помощи тегов ) и определения (при помощи тегов ). Каждое определение идет сразу за термином, который оно поясняет.

    Давайте рассмотрим это на примере.

    Допустим, мы хотим дать некоторую информацию о кодинге, сплетнях (англ. gossip — сплетни, сплетничать) и сне.

    Для начала мы ставим тег . Затем прописываем попарно теги и для кодинга, сплетен и сна соответственно.

     
    Coding
    An activity to keep you happy, even in sleep.
    Gossiping
    Can't live without it.
    Sleeping
    My all time favorite.

    See the Pen Description List by Tapas Adhikary (@atapas) on CodePen.

    Вероятно, вам любопытно, почему этот вид списков используется не так уж часто. Дело в том, что эту структуру можно создать и с помощью обычного неупорядоченного списка и CSS-стилей.

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

    Как создать хедер страницы при помощи элементов списка

    Давайте теперь рассмотрим практический пример использования списков на веб-странице. Мой любимый — применение элементов списка в хедере.

    Давайте создадим очень простой хедер с лого и тремя ссылками: Home, Products и About Us. наша HTML-структура будет выглядеть так:

    Здесь мы взяли неупорядоченный список с тремя элементами для ссылок на страницы Home, Products и About Us. Вы также видите span -элемент с текстом Logo, который обозначает лого. Здесь позже можно будет использовать подходящую картинку.

    На данный момент наш хедер выглядит так:

    Но это не то, что нам нужно. Поэтому мы добавим несколько CSS-правил и свойств, чтобы наш список начал больше походить на хедер страницы.

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

    Опять же, вы можете попробовать что-то поменять в этом коде и посмотреть, что будет.

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

    Источник

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