Html списки

Html list styles

Выпадающий список

Как сделать выпадающий список в HTML? Довольно просто, с помощью тега , который позволяет оформить элементы в виде выпадающего списка. Элементы выпадающего списка берутся в тег .

Пример.

<select>
<option selected>Выбрать породу</option>
<option>Лабрадор-ретривер</option>
<option>Золотистый ретривер</option>
<option>Померанский шпиц</option>
<option>Бигль</option>
<option>Боксер</option>
</select>

Результат.

Выбрать породуЛабрадор-ретриверЗолотистый ретриверПомеранский шпицБигльБоксер

Элемент с атрибутом selected будет выбранным, то есть стоять в начале выпадающего списка. Его можно оставить пустым.

list-style-position

The  property specifies the position of list-item marker i.e. whether the list-item marker appears inside or outside the list-item content. It can take of one of the following values.

 : Places the list-item marker as part of the list-item content.

 : Places the list-item marker before the list-item content. This is the default value.

 : Sets the initial value for the property.

 : Inherits the value from parent element.

The difference between the first two values is shown in the following demo in which the list-item content is given a background color.

See the Pen list-style-position by Aakhya Singh (@aakhya) on CodePen.

Look at the following example in which the content of list items cover more than one line.

See the Pen list-style-position example by Aakhya Singh (@aakhya) on CodePen.

If you give left padding to the li (list item) element when the ul or ol element has the  property set to , then the padding will get added before the content of the list item, thus increasing the space between the list-item marker(eg bullet or number) and the text. If the property is set to , then the list-item marker will be part of the li (list item) content. Thus, the padding will be added before the list-item marker.

CSS Lists — Controlled Counting

Some time we might want to count differently on an ordered list — e.g., starting from a number other than 1, or counting backwards, or counting in steps of more than 1.

There are following three CSS attributes which helps in controlling the list numbering.

  • <start> — allows you to start the list counting from a number other than 1.

  • <reversed> — starts the list counting reverse or down instead of up.

  • <value> — allows you to set your list items to specific numerical values.

Following is an example to show the usage of all these three attributes.

<html>
<body>
   <h2>CSS Lists - Controlled Counting</h2>
   <h3>start attribute</h3>
   <ol start="4">
      <li>Java.</li>
      <li>HTML.</li>
      <li>CSS.</li>
      <li>React.</li>
   </ol>

   <h3>reverse attribute</h3>
   <ol reversed>
      <li>Java.</li>
      <li>HTML.</li>
      <li>CSS.</li>
      <li>React.</li>
   </ol>

   <h3>value attribute</h3>
   <ol>
      <li value="2">Java.</li>
      <li value="3">HTML.</li>
      <li value="1">CSS.</li>
      <li value="4">React.</li>
   </ol>

</body>
</html>

Unordered List

To create a list marked with bullets (an unordered list, UL), use the <ul> tag:

Set List Item Markers

By default, your list marker will look like a small disc. You can change the way it looks and set different list item markers by applying the list-style-type property to the list (<ul>). By way of illustration, we’ll apply this rule to the each individual <li> element inside their parent <ul>:

Custom Bullets

You can alsospecify your own markers, such as “—”, “+”, “*”, “→”, “”, “”, etc.:

Here’s another solution if you want to use more options like positioning of the marker:

You can remove default settingsby applying these rules:

Here are more examples of custom bullets in square, triangular, arrow, heart, diamond and other shapes:

Find more examples of creating different shapes with CSS:

Set an Image as List Item Marker

You can also set an image as the list item marker using one of two ways.

Solution #1. You can apply the CSS list-style-image property to your <ul> element and indicate a path to your image. In this case, you need to resize your image manually in advance so it would fit in the list (e. g. 30 px × 30 px).

Solution #2. You can apply background-image to li::before as a more flexible solution. You don’t need to resize your image manually and you can use different icons for each <li> element if you need.

Learn more about CSS backgrounds:

list-style

Позволяет сократить код, записав все три перечисленных свойства одной строкой. Записываются правила через пробел:

ul { list-style: square inside; }

Рассмотрим пример страницы с тремя списками. Первый нумеруется цифрами в формате 01, 02, второй маркируется пользовательским рисунком (файл marker.png в папке со страницей), маркер третьего списка отключен.

HTML-код приведён ниже.

<!DOCTYPE html>
<html>
 <head>
  <title>list-style</title>
  <style>
    #spisok1 {
    list-style: decimal-leading-zero inside;
    font-weight: bold;
   }
    #spisok2{
    list-style: outside url("marker.png");
   }
    #spisok3{
    list-style-type: none;
    font: oblique small-caps 12pt/1.2 Arial, sans-serif;
   }
  </style>
 </head>
 <body>   
    <ol id="spisok1">
      <li>Первый пункт</li>
      <li>Второй пункт</li>
      <li>Третий пункт</li>
    </ol>
    <ul id="spisok2">
      <li>Первый пункт</li>
      <li>Второй пункт</li>
      <li>Третий пункт</li>
    </ul>
    <ol id="spisok3">
      <li>Первый пункт</li>
      <li>Второй пункт</li>
      <li>Третий пункт</li>
    </ol>
 </body>
</html>

Браузер отобразит следующую страницу.

Дата размещения/обновления информации: 29.04.2021 г.
Сообщить об ошибке

CSS List Colors

When you’re designing a list, you may decide that you want the list to display background colors.

Suppose the bakery asks us to set the background color of the entire list to light blue and to use a pink background color for each item in the list. We can use the CSS background property to accomplish this task, like so:

ul {
	background: lightblue;
	padding: 10px;
}

ul li {
	background: pink;
	margin: 10px;
}

Our code returns:

<ul>
	<li>Butterfly Cakes</li>
	<li>Chocolate Traybake</li>
	<li>Lemon Pound Cake</li>
	<li>Peanut Butter Flapjacks</li>
	<li>Chocolate Muffins</li>
</ul>

In our code, we applied a light blue background color using the background property to the

element, which creates an unordered list. We also gave the

element a 10px padding using the padding property.

We also applied a pink background to and created a 10px margin around each list item.

We accomplished this by including our styles in a “ul li” selector, as you can see above. This selector states that the pink background and 10px margin should be applied to all

tags enclosed within a

tag.

Basic HTML List Example

First, let’s look at an example of a list in HTML. Suppose a local bakery asks us to create a web page that includes a list of recipes for customers’ home use.

Here is the basic HTML code we will use to define our list:

<ul>
	<li>Butterfly Cakes</li>
	<li>Chocolate Traybake</li>
	<li>Lemon Pound Cake</li>
	<li>Peanut Butter Flapjacks</li>
	<li>Chocolate Muffins</li>
</ul>

Our list appears as follows:

Our list contains five items. We enclose each list item within

tags. (“li” stands for “list item.”) We enclose these

tags within a

tag. The

tag identifies an unordered list.

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Find Your Bootcamp Match

Since this is an unordered list, our web browser places a bullet point before each of the items in the list. (If it were an ordered list, our web browser would place an orderable value—usually a number or a letter—before each item in the list.)

Now, let’s explore how we can style a list using the list-style property.

Вид маркера в списке.

Если Вы помните, то в чистом HTML вид маркера в списке определял атрибут type и одно из его возможных значений, в CSS данную задачу берёт на себя свойство: list-style-type которое, в свою очередь, тоже имеет свои стандартные значения определяющие вид маркера как всего списка сразу, так и его отдельного «пункта».

Значения list-style-type:

  • disc — Диск. (по умолчанию для <ul>)
  • circle — Полый круг.
  • square — Квадрат.
  • decimal — Арабские цифры. (по умолчанию для <ol>)
  • lower-roman — Строчные римские цифры.
  • lower-alpha — Строчные буквы.
  • upper-roman — Заглавные римские цифры.
  • upper-alpha — Заглавные буквы.
  • none — Маркер отсутствует.

Пример:

<!DOCTYPE HTML PUBLIC «-//W3C//DTD HTML 4.01 Transitional//EN» «http://www.w3.org/TR/html4/loose.dtd»><html><head><title>Вид маркера в списке</title></head><body> <ul style=»list-style-type: square«><li>Пункт 1.<li>Пункт 2.<li style=»list-style-type: circle«>Пункт 3 (особенный).</ul><ul style=»list-style-type: upper-roman«><li>Пункт 1.<li>Пункт 2.<li>Пункт 3.</ul></body></html>

смотреть пример  

🌈 Changing the Color

The most basic way to make your lists look better, is to change the color of the list markers. We can do that just like we would change the color of normal text.

What if you need to support older browsers? You can apply the color to the and wrap the text inside it in another element. Like this:

HTML

Enter fullscreen modeExit fullscreen mode

CSS

Enter fullscreen modeExit fullscreen mode

Or create a fully custom marker with . More on that later.

Custom Text

You might be thinking: Okay, but is changing color all that can do?

No. Far from it. It lets us to change the content of the list marker, by using the aptly named property.

You can use any text as , including Unicode symbols like the ones above or even emoji…

Ordered Lists

The ordered list element, , works very much like the unordered list element; individual list items are created in the same manner. The main difference between an ordered list and an unordered list is that with an ordered list, the order in which items are presented is important.

Because the order matters, instead of using a dot as the default list item marker, an ordered list uses numbers.

Ordered lists also have unique attributes available to them including and .

Ordered Lists Demo

See the Pen Ordered Lists by Shay Howe (@shayhowe) on CodePen.

Start Attribute

The attribute defines the number from which an ordered list should start. By default, ordered lists start at . However, there may be cases where a list should start at or another number. When we use the attribute on the element, we can identify exactly which number an ordered list should begin counting from.

The attribute accepts only integer values, even though ordered lists may use different numbering systems, such as roman numerals.

Start Attribute Demo

See the Pen Start Attribute by Shay Howe (@shayhowe) on CodePen.

Reversed Attribute

The attribute, when used on the element, allows a list to appear in reverse order. An ordered list of five items numbered to may be reversed and ordered from to .

The attribute is a Boolean attribute, and as such it doesn’t accept any value. It is either true or false. False is the default value; the value becomes true when the attribute name appears on the element.

Reversed Attribute Demo

See the Pen Reversed Attribute by Shay Howe (@shayhowe) on CodePen.

Value Attribute

The attribute may be used on an individual element within an ordered list to change its value within the list. The number of any list item appearing below a list item with a attribute will be recalculated accordingly.

As an example, if the second list item has a attribute value of , the number on that list item marker will appear as if it is the ninth item. All subsequent list items will be numbered upwards from .

Create the marker

When using you have access to all CSS properties and not just a subset like with .

You are however responsible for setting the marker’s content, spacing between the marker and the list item’s text, and proper alignment.

As an example, here’s how to create the objectively best-looking list of all time. Explanations are included in the comments.

The code above results in this:

A few notes:

  • Using the background property for the marker’s image allows us to scale and adjust it more easily.
  • If you want to create custom image bullets for an unordered list using & , you have to set in order for the marker to be rendered.

That’s all, you’re now a master of list styling.

Использование изображений в качестве маркеров списка.css-свойство list-style-image

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

  • url – относительный или абсолютный путь к файлу изображения, указываемый в скобках с использованием
    одиночных или двойных кавычек или без них, например,
    {list-style-image: url(«http://html.net/image_1.png»)};
  • none – используется по умолчанию и указывает браузеру, что следует применять стандартный маркер
    вместо изображения.

Кстати, в данном списке маркеры представляют собой не что иное, как изображения в виде кружков.

Card Like List Styles

In this section,we will be designing our list styles to look like CSS cards. So yeah, without further ado, lets get on to it. Firstly we will be adding html for default list styling. And then slowly as we move ahead we will be styling those lists. And make it look like a card.

Excited? Well lets get right on to it.

Adding Default Lists

Just as introduced in the introduction section, we will be adding unordered list html without adding any CSS. So that, we can look into it and observe what more can we modify.

It’s just a basic and pair. Within each list items you can see a text and an arrow. The arrow is obtained from font awesome. So we need to add font-awesome CDN link to our page.

I’ve added the following CDN link in the head section of the page.

Now, you should be seeing a default bulleted list appearing on your page. That’s because for now, we haven’t yet added any custom css for the added html list up till this section of the tutorial.

And that’s the html’s way of presenting the ul list style to the page.

Adding a Header Text

Just for extra look up, lets create a simple header for the list item. You can be as dynamic you want. But for this tutorial I’ll be adding header as below.

It must be obvious that the above head should lie above all the pair. The additional tag is just a horizontal divider line. That, for now is covering the entire width of the horizonal row. But let it be.

Adding CSS

In this section, We will be adding CSS to our list style example. Firstly, as this list style shall be customized to look like a card. Lets do that. Lets make our List style to look like a card

Pretty cool, right? With just some tinge of shadow appearing on the block, the entire list style block now looks like a card menu.

Now, Lets move our list to a better position, just to make it a bit more presentable.

Positioning the Block to Center

I’ve used the CSS absolute style method to move our list to the center of the page.

Setting the above ul list style to absolute, I’ve removed it from the original flow of the page. Then I moved the entire block to 50% left and from top.

However this doesn’t consider the width or the height of the block. Rather, arranges the block with its top left corner to be at the center of the page. So to make the center of the block to appear at the center of the page. I’ve translated the block to its 50% width left and 50% height top.

Now you should be seeing the element positioned at the center of the block.

Styling our Header Text

Now lets add style to our header text.

Okay, That was just some basic arrangement. Now just for a suitable background setup, I’ve added the background color to our body as below. Well that’s just what my conscience led me to do. Once again, be as dynamic as you want to custom build your styles.

Styling the List style with CSS

Okay, that bulleted default look of the list style is so boring. Now, in this section of the tutorial, we will be custom building CSS for the html list and try to make it look as stunning as possible.

Okay, Now lets see what we have here. We have added padding, gave size to the font and styled with some font- family. That’s just basic, right? The only eye-catching feature should be and if you are not so familiar with gird layout, I suggest you do.

Lets understand what grid layout and the additional mean. Grid layout is a 2-d layout model. With it you can have responsive block design in 2 dimensions considering both horizontal and vertical configuration. Now with we have two distinct value with unit indicating fraction.

If you add up those fractions, you have . That means we have divided our columns into 9 equal blocks. The first block covering the 8th fraction while the last block covering only a fraction of the entire block.

This sets the gap between our arrow icon and the list item text.

Miscellaneous CSS to List style

We have already achieved a great custom built list with above HTML and CSS in this tutorial. However, as a part of some extra arrangement and some hover effects, I’ve added CSS below.

These are obtained as a result of some repeated trial and error experimentation with some padding and margin.

There we have it our final screenshot of the card style of the unordered list built by using HTML and CSS.


Card List style

list-style-type

The CSS property controls the bullets used by the
element, and the numbering used by the element. The following sections look
at both the and element.

list-style-type : ul

For the element you can use these property values:

Here is how you set the for a list element:

ul {
    list-style-type: disc;
}

This example sets the CSS property to for
all elements.

Here is how the possible values (, and )
look when applied to a element:

It is actually possible to apply the CSS property to each
element, instead of to the whole element.
Here is how that looks in code:

<ul>
    <li style="list-style-type: disc;"><code>disc</code></li>
    <li style="list-style-type: circle;"><code>circle</code></li>
    <li style="list-style-type: square;"><code>square</code></li>
</ul>    

The result will look like the example above that shows the three different bullet types (disc, circle and square).

list-style-type : ol

The CSS property can also be used to style elements.
Instead of bullets you can set what kind of numbering scheme the element is
to use. The valid values for the property for
elements are:

  • decimal
  • decimal-leading-zero
  • upper-alpha
  • lower-alpha
  • upper-roman
  • lower-roman
  • lower-greek

Here is a CSS rule setting the to :

ol {
    list-style-type : upper-alpha;
}

These following lists show how the number scheme looks with the 6 different possible values.

  1. decimal
  2. decimal
  3. decimal
  1. decimal-leading-zero
  2. decimal-leading-zero
  3. decimal-leading-zero
  1. upper-alpha
  2. upper-alpha
  3. upper-alpha
  1. lower-alpha
  2. lower-alpha
  3. lower-alpha
  1. upper-roman
  2. upper-roman
  3. upper-roman
  1. lower-roman
  2. lower-roman
  3. lower-roman
  1. upper-latin
  2. upper-latin
  3. upper-latin
  1. lower-latin
  2. lower-latin
  3. lower-latin
  1. lower-greek
  2. lower-greek
  3. lower-greek

Types of Lists

HTML provides three types of lists with accompanying HTML tags. These are:

  • Ordered lists (<ol>) – These include numbers before each item.
  • Unordered lists (<ul>) – The lists have bullet points that you can swap with images before each item.
  • Definition lists (<dl>) – They are items lists with corresponding descriptions.

All the list types have their default HTML style. In addition to that, CSS provides various properties to make your lists pleasing. The CSS list properties let you:

  • Alter item markers ordered and unordered lists
  • Define image as an item marker
  • Set background colors for lists and items

List Item Markers

The list-style-type property is used to specify the type of marker used for items in a list.

Unordered List Item Markers

Suppose the bakery asks us to show what their list would look like with a circle bullet point versus a square bullet point preceding each list item. We can use the following code to create these designs for the bakery:

styles.css

li.circlebulletPoint {
	list-style-type: circle;
}

li.squarebulletPoint {
	list-style-type: square;
}

index.html

<ul>
	<li class="circlebulletPoint">Butterfly Cakes</li>
	<li class="squarebulletPoint">Chocolate Traybake</li>
	<li>Lemon Pound Cake</li>
	<li>Peanut Butter Flapjacks</li>
	<li>Chocolate Muffins</li>
</ul>

Our code returns:

As you can see, our first list item uses the circle bullet point marker style. We accomplished this by assigning the class value “circlebulletPoint”—and therefore that value’s corresponding style—to our first list item. We assigned the class value “squarebulletPoint” to our second list item, so the web browser displays a square bullet point before that item.

There are other list-style-types which can be applied to a list, which are:

  • disc
  • circle
  • decimal
  • decimal-leading-zero
  • lower-roman
  • upper-roman
  • lower-greek
  • lower-latin
  • upper-latin
  • armenian
  • georgian
  • lower-alpha
  • none

We discuss a few of these that apply to ordered lists in the next section.

Ordered List Item Markers

Ordered lists have their own item marker styles.

Suppose we want the bakery’s recipes to be displayed in an ordered list. We want to see what our list would look like with its order marked by a lowercase alphabetical letter preceding each item in the list, and what it would look like with an uppercase Roman numeral preceding each item in the list. We could use the following code to accomplish this task:

styles.css

li.alpha {
	list-style-type: lower-alpha;
}

li.roman {
	list-style-type: upper-roman;
}

index.html

<ol>
	<li class="alpha">Butterfly Cakes</li>
	<li class="roman">Chocolate Traybake</li>
	<li>Lemon Pound Cake</li>
	<li>Peanut Butter Flapjacks</li>
	<li>Chocolate Muffins</li>
</ol>

Our code returns:

In this example, we used an ordered list (<ol>) instead of an unordered list. This allows us to order our list with numbers (or letters, etc.). Then, we marked the first item in our list with a lowercase alphabetical letter and the second item in our list with an uppercase Roman numeral.

Unordered Lists

An unordered list is a list in which the order of the list items does not matter. Unordered lists should be used when rearranging the order of the list items would not create confusion or change the meaning of the information on the list.

The element opens and closes an unordered list. The items on the list are contained between list item, , tags. A simple unordered list containing three items could be created with the following HTML.

Unless CSS rules are created to change the appearance of the list, the default presentation of an unordered list is to add a disc-style bullet point on the left-hand side of each list item and to indent the entire list.

Here’s how our short unordered list renders in a browser:

  • Item A
  • Item B
  • Item C

Custom Image Bullets

Okay, we can change the color, style, and text content of list markers, but what if we want something completely custom? We’ll have to use images.

To do that, we set an image as the marker’s content using the CSS function.

Fully Custom List Markers

If all of the above options still aren’t enough for you, there’s still one more option. One that allows us to do anything we want with our list markers. It’s more work and a bit of a hack, but it’s useful if all else fails.

We can use the pseudo element to create our own markers. This method allows us to create custom backgrounds for our markers, easily scale image bullets and more.

List Style Shorthand Property

We have been discussing the sub properties of the list-style property. These have allowed us to apply individual styles to our list.

However, there is a more efficient way of styling lists. Instead of using each individual subproperty to style a list, we can use the list-style shorthand property. Here is the syntax for the list-style shorthand property:

ul {
	list-style:   ;

The order of values specified above is the order you need to use with the list-style shorthand property. If you do not specify a value for one of the three sub properties that make up the shorthand syntax, the web browser will use that subproperty’s default value.

Suppose we want to style our list of baked goods recipes with a cake image and also move each list item marker to the outside of our list. We can do so using this code:

styles.css

ul {
	list-style: outside url('https://img.icons8.com/small/16/000000/cake.png');
}

index.html

<ul>
	<li>Butterfly Cakes</li>
	<li>Chocolate Traybake</li>
	<li>Lemon Pound Cake</li>
	<li>Peanut Butter Flapjacks</li>
	<li>Chocolate Muffins</li>
</ul>

Our code returns:

Our list now uses the cake image for each list item marker. In addition, each list item marker is styled outside our list.

list-style-type

The  specifies the type of list-item marker. It can accept one of the following values. However, the default values for  ul  (unordered list) and ol(ordered list) are  and  respectively.

, , , , , , , , , , , , , , , , , , , , , , , , , 

The value  hides the list marker. All the above listed values are demonstrated in the following demo.

See the Pen list-style-type by Aakhya Singh (@aakhya) on CodePen.

In the above demo, ul:nth-of-type(1) represents the first ul element. Similarly, this selector is used for representing other ul elements.

Some of the values like hebrew, hiragana, hiragana-iroha, katakana, and katakana-iroha are not supported by IE and versions of Opera till Opera 12. Firefox 32 and its earlier versions do not support some of the values like telugu, bengali and urdu.

You can also give different styles to the list item markers of different items of the same list as shown below.

See the Pen Different list item marker styles in a list by Aakhya Singh (@aakhya) on CodePen.

Here, ul li:nth-child(1) represents the first li child of the ul element.

The  property can be applied to list elements as well as elements given . You can learn more about the values which can be given to this property from CSS list-style-type values.

Display type #

All of our and properties know to style elements because they have a default display value of list-item. You can also make things that aren’t an into a list item.

You do this by adding the property . One example of using is if you want a hanging bullet on a heading, so that you can change it to something else with . The following example shows a heading using for styling purposes, with a list using correct list markup below.

While you can turn anything into a list-item view with , you should not use this instead of using correct list markup, if the content you are styling really is a list. Changing the visual appearance of an item to a list item does not change how accessibility services read and recognize the item, so it will not be read as a list item to screen readers or switch devices. You should always use semantic markup and create lists with whenever possible.

Test your knowledge of lists

The element preceding a list-item is called a

::bullet ::pencil ::marker ::counter

Try again.

Try again.

Correct!

Try again.

The three types of HTML lists are

Correct!

Try again.

Correct!

Try again.

Correct!

Try again.

Which two styles in this list will apply styles to a ::marker?

Correct!

Try again.

Correct!

Try again.

Styling Lists

List typography is usually best styled to match the typography of the website’s paragraph text. List-specific styling can be accomplished with CSS.

There are three list properties that can be styled with CSS:

  • : Defines the marker type that preceeds each list item. Common values include (the default unordered list style type), (the default ordered list style type), circle, square, lower- or upper-roman, and lower- or upper-latin, although several additional styles may also be used.
  • : Determines whether the list item marker should be placed the content box, or of the content box in the item’s left-hand padding area.
  • : An image can also be used as the item marker. This property is used to specify the image file to be used.

Each of these three properties can be applied seperately by using the individual property names or simultaneously with the shorthand property. The property syntax includes the list style type, position, and image values in that order. For example, if we wanted to select the square marker, position it inside the content box, and also specify an image file, our CSS would look something like this:

Since we’ve specified both a list marker and an image, the image will be used unless it is unavailable, in which case the square marker will be displayed.

Custom Ordered Lists

To change the content of an ordered list marker, we need to know which item it belongs to. We need to know its position in the list. That’s where CSS counters come in.

We need to create a counter on the list, and increment it on every list item. Then retrieve the current value of the counter using the CSS function. We use the result of this function as the value of the property.

Enter fullscreen modeExit fullscreen mode

Let’s go through the code, to understand what’s happening.

We use to create a new counter named . The name is arbitrary and completely up to you. But why is the property called counter-reset? Because the counter is actually global and we need to reset its value on every list. That’s why we have to set it on the and not the list items.

We’ve created our counter, but it’s useless if its value never changes. We need to increment it on every list item. To do that we set on our ‘s.

Now that we have an auto-incrementing value, we use it in the property of our marker. And here’s where the magic happens. We can combine the value of our counter with other strings, optionally separated by whitespace.

A FEW NOTES:

  • In the example, I imported some fonts from Google Fonts. It’s not necessary but I’m using it to distinguish between the list item’s content and the marker.
  • Because the marker’s content in the example got pretty long, it was possible for it to go off the screen in some circumstances. That’s why I used to move the marker inside the list item’s box.
  • You can put a number after the counter name to start from a different value. It would look something like this: and the first three items of that list would have numbers 6, 7, and 8.
  • Counters can be used on any html element, not just lists.

List UI Design Style with HTML and CSS

This is a fun idea by Collin Smith. In the event that you are searching for some cool enlivened list styles, this one may dazzle you. On floating to the list will give a legitimate effect to the clients and other visiting people. The numbers on the foundation additionally can be seen appropriately. Be that as it may, on the off chance that you like to be predictable in your structure, you can stay with one movement impact. Despite the fact that the idea looks complex, the code structure is exceptionally straightforward.

The designer has utilized just CSS3 content to make this wonderful theoretical structure. In light of this basic code structure, you can without much of a stretch use this code in your plan. You should simply to tune the plan according to your necessity and use it on your site or application.

Нумерованные списки

В нумерованный список браузер автоматически вставляет номера элементов по порядку, начиная с некоторого значения (обычно 1). Это позволяет вставлять и удалять пункты списка, не нарушая нумерации, так как остальные номера автоматически будут пересчитаны.
Нумерованные списки создаются с помощью блочного элемента <ol> (от англ. Ordered List – нумерованный список). Далее в контейнер <ol> для каждого пункта списка помещается элемент <li> (от англ. List Item – пункт списка). По умолчанию применяется нумерованный список с арабскими числами.
Тег <ol> имеет следующий синтаксис:

Элементы нумерованного списка должны содержать несколько элементов списка, как показано в следующем примере:

Пример: Нумерованный список

  • Результат
  • HTML-код
  • Попробуй сам »

Пошаговая инструкция

  1. Достать ключ
  2. Вставить ключ в замок
  3. Повернуть ключ на два оборота
  4. Достать ключ из замка
  5. Открыть дверь

Иногда при просмотре существующих кодов HTML вы будете встречать аргумент type в элементе <ol>, который используется для указания типа нумерации (буквы, римские и арабские цифры и т.п.). Синтаксис:

Здесь: type – символы списка:

  • A — прописные латинские буквы (A, B, C . . .);
  • a — строчные латинские буквы (a, b, c . . .);
  • I — большие римские цифры (I, II, III . . .);
  • i — маленькие римские цифры (i, ii, iii . . .);
  • 1 — арабские цифры (1, 2, 3 . . .) (применяется по умолчанию).

Если вы хотите, чтобы список начинался с номера, отличного от 1, следует указать это при помощи атрибута start тега <ol>.
В следующем примере показан нумерованный список с большими римскими цифрами и начальным значением XLIX:

Пример: Применение атрибутов type и start.

  • Результат
  • HTML-код
  • Попробуй сам »
  1. Перепела
  2. Фазаны
  3. Куропатки
  4. Павлины

Нумерацию можно начинать и с помощью атрибута value, который добавляется к элементу <li> следующим образом:

В этом случае последовательная нумерация списка прервётся и с этого пункта нумерация начнётся заново, в данном случае с семи.

Пример использования атрибута value тега <li>, который позволяет изменить номер данного элемента списка:

Пример: Применение атрибута value

  • Результат
  • HTML-код
  • Попробуй сам »
  1. Первый пункт списка
  2. Второй пункт списка
  3. Третий пункт списка

В этом примере «Первый пункт списка» будет иметь номер 1, «Второй пункт списка» – номер 7, а «Третий пункт списка» – номер 8.

::marker pseudo-element #

The marker element is the bullet, hyphen, or roman numeral that helps indicate each item in your list.

If you inspect the list in DevTools, you can see a element for each of the list items, despite not declaring any in HTML. If you inspect the further, you’ll see the browser default styling for it.

When you declare a list, each item is given a marker, despite there being no bullet point or roman numeral in your HTML. This is a pseudo-element because the browser generates it for you, and provides a limited styling API to target it. Learn more about the anatomy of the CSS bullet. currently has in Safari.

Marker box

In the CSS layout model, list item markers are represented by a marker box associated with each list item. The marker box is the container which typically contains the bullet or number.

To style the marker box, you can use the selector. This allows you to select just the marker instead of styling based on the entire list.

Marker styles

Now that you have selected the marker, let’s look at the styling properties available to this selector. You can learn more about Custom bullets with CSS ::marker on web.dev.

There are quite a few allowed CSS Properties:

list-style-position

The CSS property is used to set the position of the bullet
or numbers. The CSS property can take one of 2 values:

Here is an example that sets the to :

ul {
    list-style-position: outside;
}

Here are two unordered lists — one with the set to
and one set to .

  • This text uses the value which is especially visible
    when the text for a list item spans more than one line.
    This text uses the value which is especially visible
    when the text for a list item spans more than one line.
  • This text uses the value which is especially visible
    when the text for a list item spans more than one line.
    This text uses the value which is especially visible
    when the text for a list item spans more than one line.
  • This text uses the value .
    This text uses the value .
    This text uses the value .
    This text uses the value .
  • This text uses the value .
    This text uses the value .
    This text uses the value .
    This text uses the value .

Notice how the value renders the bullet as part of the list item text. When the list item
text spans more than one line, the text wraps and starts under the bullet.

With the avlue the bullet is rendered separately from the text. The text wraps and
starts under the text, not the bullet, when the text spans multiple lines.

Понравилась статья? Поделиться с друзьями:
Setup Pro
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: