Css list style: the best guide on how to style css lists

List-style

Position the List Item Markers

Web browsers also dictate how CSS list items are positioned. You might want to change the default look.

First, you might want to remove the margin to the left of your list (apply margin-left with any value that suits you). 

Second, you can add the list-style-position: inside; so that the bullet points would be inside the list item and part of the text. The result will be a CSS list indent.

Third, you can add margin-bottom to all <li> elements except for the last one so that your list would be more readable.

If you want the text to be aligned alongone line vertically, simply remove list-style-position: inside;:

You can use a shorthand property to set all the list properties in one declaration: ul {list-style: none inside url(«images/shark-small.png»);}

list-style-position

Определяет положение маркера: либо он вынесен за границу элемента списка (list-style-position: outside), либо текст его обтекает (list-style-position: inside).

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

<!DOCTYPE html>
<html>
 <head>
  <title>list-style-position</title>
  <style>
    #spisok1 {
    list-style-position: inside;
   }
    #spisok2 {
    list-style-type: outside;
   }
  </style>
 </head>
 <body>   
    <ul id="spisok1">
      <li>Вы просто посмотрите, чем отличаются inside от outside.</li>
      <li>В случае с inside маркер прямо-таки вписывается в список, не выходя за его пределы и не мешая вёрстке. Текст обтекает его, маркер как бы внутри.</li>
      <li>Значение outside выносит маркер за пределы списка.</li>
    </ul>
    <ul id="spisok2">
      <li>Вы просто посмотрите, чем отличаются inside от outside.</li>
      <li>В случае с inside маркер прямо-таки вписывается в список, не выходя за его пределы и не мешая вёрстке. Текст обтекает его, маркер как бы внутри.</li>
      <li>Значение outside выносит маркер за пределы списка.</li>
    </ul>
 </body>
</html>

В результате создаётся такая страница:

Using List Item Markers in CSS

With CSS, the list-style-type property lets you specify the marker you want for the items within a list. It determines the loof of markers on both unordered and ordered lists. Keep in mind that the color set for the element determines the color of the marker.

– Choosing Item Markers for Unordered List

CSS allows you to choose different item markers for each item in a list. For the bakery list items, you can choose to use circle and square bullet points. Below is the ul style CSS code for creating these designs:

li.circle

{

list-style-type: circle;

}

li.square

{

list-style-type: square;

}

<ul>

<li class=”circle”>Chocolate Muffins</li>

<li class=”square”>Chocolate Traybake</li>

<li>Peanut Butter Flapjacks</li>

<li>Butterfly Cakes</li>

<li>Lemon Pound Cake</li>

</ul>

It will result in the first item having a circle item marker. The second item, instead, will have a square item marker since it is the type of value the “square” class assigns to it. Other CSS list-style-types include:

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

Note: There are many more predefined list item markers you can use, such as Chinese numbering and traditional Hebrew, among others.

– Item Markers for Ordered Lists

Ordered lists offer different ways of altering their item markers. For instance, you can choose to use lower or upper case roman numbers. Also, you can use the default standard numbers beginning with one.

In the example above, you can opt for lowercase alphabetical letters as item markers or uppercase Roman numerals. You could try both list styles in the first two items of our bakery case as follows.

li.loweralpha

{

list-style-type: lower-alpha;

}

li.upperroman

{

list-style-type: upper-roman;

}

<ol>

<li class=”alpha”>Chocolate Muffins</li>

<li class=”roman”>Chocolate Traybake</li>

<li>Peanut Butter Flapjacks</li>

<li>Butterfly Cakes</li>

<li>Lemon Pound Cake</li>

</ol>

The result will be a lowercase alphabetical letter for the first list item and an uppercase roman numeral for the second list item.

– Removing Default List Item Marker Style

CSS provides three properties that you can use to remove the default style in a list. These properties are padding, list-style-type, and margin. If you wish to get rid of any type of item marker before list items, you can set the list-style-type property to none.

Below is an example of how you can remove any item marker in a list using the list-style-type property.

ul

{

list-style-type: none;

}

– Using CSS Marker Position

In CSS, the list-style-position property sets the position of the list item markers within a list. Item markers can appear either inside or outside of a list.

An inside value for this property results in a text that appears immediately after the item marker. The outside value results in a gap between the item list marker and the text items.

Here are the CSS rules that show how you can apply this property in both cases:

ul.one

{

list-style-position: inside;

}

ul.two

{

list-style-position: outside;

}

By default, browsers apply the outside position to lists. So, if you fail to specify another list-style-position value, the browser will automatically use the default position for list item markers.

– Setting Image Markers

With CSS, you can also set custom markers using images. To set an image as a list item marker, use the list-style-image property in CSS. Normally, the property uses a URL address of the image as its value.

Say you wish to change the list item markers for the bakery to cake images instead of numbers or bullets. You can count on the code below to do this:

ul

{

list-style-image: url(“https://…”);

}

This way, you can avoid using the default list item markers by setting your own.

padding

You can increase the distance between the bullet or number and the text for the corresponding list item by
setting the padding CSS properties for the elements. Here is an example:

<ul>
    <li style="padding-left: 20px">With padding</li>
    <li>Without padding</li>
</ul>

This example sets the to . If the or
element has the set to (or omitted), then setting the
property of the element will increase the space between the bullet / number
and the text. Here is how that looks on a live element:

  • With padding
  • Without padding

If, however, the or element has the CSS property
set to , then the padding will be applied before the bullet / number, because the
bullet / number is considered rendered inside the element. Padding set on the
element is then rendered to the left of the bullet. Here is how that looks on a live
element:

  • With padding
  • Without padding

The padding CSS properties can also be used to set the distance between individual
elements. Here is an example:

<style>
    ul>li {
        padding-bottom: 20px;
    }
</style>

<ul>
    <li>Item one</li>
    <li>Item two</li>
</ul>

This example sets the bottom padding of each list item ( element) to .
Thus, there will be 20px of blank space below each element.

Here is how that looks applied to a live element:

  • Item one
  • Item two

In some browsers you may have to use the margin CSS properties instead of the padding CSS properties
to make distance between the elements.

Marker Position

The list-style-position property is used to specify the position of the list item markers in a list.

There are two positions in which the item markers for a list can appear: inside and outside. If the list markers appear inside the list, the text will appear directly next to the item markers; if the list markers appear outside the list, there will be a gap between the list markers and the text items in the list.

Here are two example CSS rules which demonstrate how the list-style-position can be applied in both of these states:

ul.a {
	list-style-position: outside;
}

ul.b {
	list-style-position: inside;
}

In our first list, we used the list-style-position: outside style. This is the default style applied to lists. As such, had we not specified this or any other list-style-position in our block of code, the browser would have defaulted to this positioning for list item markers. The following is the code for our bakery list that uses this style:

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

The code returns:

In this style, list item markers (in this case, bullet points) appear outside of our list items.

In our second list, we have specified the position of our list item markers as “inside.” The following is the code for our bakery list that uses this style:

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

The code returns:

It’s hard to tell but the position of our list item markers is now outside the list item.

Conclusion

In this article, we have discussed the whole concept of CSS List and how it helps to arrange items and elements.

If you are interested in learning more about CSS and other related concepts, you can enroll in Simplilearn’s exclusive Full Stack Web Development Certification Course and accelerate your career as a software developer. The program comprises a variety of software development courses, ranging from the fundamentals to advanced topics. 

Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. You can take up any of these courses to upgrade your skills and advance your career.

Стиль обтекания маркера списком.

Свойство list-style-position указывает браузеру на то, как следует отображать текст в списке относительно его маркеров. По умолчанию маркеры находятся в стороне от текста списка, но можно сделать так, что они будут обтекаться текстом.

Возможных значений свойства list-style-position всего два:

  • outside — Маркер находится в стороне от списка.(по умолчанию)
  • inside — Маркер обтекается текстом.

Пример для наглядности:

<!DOCTYPE HTML PUBLIC «-//W3C//DTD HTML 4.01 Transitional//EN» «http://www.w3.org/TR/html4/loose.dtd»><html><head><title>Обтекание маркера текстом</title><style type=»text/css»>body {margin: 0px;background: #e8e8e8}div {width: 300px;height: 200px;float:left;margin: 10px;padding: 10px;border: RGB(25, 125, 25) 2px ridge;background: #fff}h3 {text-align: center}</style></head><body><div><h3>Здесь маркер обтекается текстом:</h3><ul style=»list-style-position:inside«><li>Пункт, в котором говорится о том, что хорошо бы было сделать, что-то там, где это что-то еще не сделано.<li>Пункт, в котором говорится о том, что неплохо бы было сделать, нечто там, где это нечто еще не сделано.</ul></div> <div><h3>А здесь нет:</h3><ul style=»list-style-position:outside«><li>Пункт, в котором говорится о том, что хорошо бы было сделать, что-то там, где это что-то еще не сделано.<li>Пункт, в котором говорится о том, что неплохо бы было сделать, нечто там, где это нечто еще не сделано.</ul></div> </body></html>

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

CSS Свойства

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-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-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-eventspositionquotesresizerighttab-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

List Item Styling

List Style Type Property

Any property value can be added to either unordered or ordered lists. With this in mind, it is possible to use a numeric list item marker on an unordered list and a nonnumeric marker on an ordered list.

HTML
CSS

List Style Type Values

As previously mentioned, the property comes with a handful of different values. The following list outlines these values as well as their corresponding content.

List Style Type Value Content
No list item
A filled circle
A hollow circle
A filled square
Decimal numbers
Decimal numbers padded by initial zeros
Lowercase roman numerals
Uppercase roman numerals
Lowercase classical Greek
Lowercase ASCII letters
Uppercase ASCII letters
Traditional Armenian numbering
Traditional Georgian numbering

Using an Image as a List Item Marker

There may come a time when the default property values are not enough, and we want to customize our own list item marker. Doing so is most commonly accomplished by placing a background image on each element within a list.

The process includes removing any default property value and adding a background image and padding to the element.

In detail, the property value of will remove existing list item markers. The property will identify a background image, along with its position and repeat value, if necessary. And the property will provide space to the left of the text for the background image.

HTML
CSS

Image List Item Marker Demo

See the Pen Image List Item Marker by Shay Howe (@shayhowe) on CodePen.

List Style Position Property

By default the list item marker is to the left of the content within the element. This list style positioning is described as , meaning all of the content will appear directly to the right, outside of the list item marker. Using the property, we can change the default value of to or .

The outside property value places the list item marker to the left of the element and doesn’t allow any content to wrap below the list item marker. The inside property value (which is rarely seen or used) places the list item marker in line with the first line of the element and allows other content to wrap below it as needed.

HTML
CSS

List Style Position Property Demo

See the Pen List Style Position Property by Shay Howe (@shayhowe) on CodePen.

The list style properties discussed thus far, and , can be combined into one shorthand property value. When using the property, we can use one or all list style property values at a time. The order of these shorthand values should be followed by .

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

Нумерованный список — это список элементов, порядок следования которых имеет значение. Иногда такие списки также называют упорядоченными. Типичным примером упорядоченного списка является запись последовательности действий или выполняемых операций.

Для организации нумерованного списка используется HTML-элемент (сокр. от англ. ordered list — «упорядоченный список»). Оба тега элемента — открывающий и закрывающий — являются обязательными (см. ).

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

Пример разметки простого нумерованного списка:

<p>Текст предшествующего абзаца.<p/>
<ol>
  <li>Первый элемент списка.</li>
  <li>Второй элемент списка.</li>
  <li>Третий элемент списка.</li>
</ol>

Вид в браузере:

В открывающем теге элемента могут присутствовать универсальные атрибуты и атрибуты событий. Кроме того, в теге могут быть использованы собственные атрибуты: , и .

Необязательный булев атрибут позволяет при необходимости задать в списке обратный порядок нумерации, например:

<ol reversed>
  <li>Первый элемент списка.</li>
  <li>Второй элемент списка.</li>
  <li>Третий элемент списка.</li>
</ol>

Результат в браузере:

Необязательный атрибут позволяет указать число, с которого начнётся нумерация в списке. При записи значения атрибута следует использовать арабские цифры (1, 2, 3 и т.д.), даже когда установлена нумерация в буквах или римских цифрах. Например, чтобы начать нумерацию с буквы «d» или римской «IV», укажите .

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

<ol>
  <li>Первый элемент списка.</li>
  <li>Второй элемент списка.</li>
  <li>Третий элемент списка.</li>
</ol>
<p><i>Примечание:</i> Текст примечания к
  третьему пункту списка.</p>
<ol start="4">
  <li>Четвёртый элемент списка.</li>
  <li>Пятый элемент списка.</li>
  <li>Шестой элемент списка.</li>
</ol>

Вид в браузере:

Необязательный атрибут позволяет задать тип нумерации в списке. Возможные значения атрибута:

  • — использовать арабские цифры (значение по умолчанию);
  • — использовать римскую нумерацию строчными символами;
  • — использовать римскую нумерацию заглавными символами;
  • — использовать буквенную нумерацию строчными символами;
  • — использовать буквенную нумерацию заглавными символами.

Пример использования атрибута:

<ol type="a">
  <li>Первый элемент списка.
  <li>Второй элемент списка.
  <li>Третий элемент списка.
  <li>Четвёртый элемент списка.
</ol>

Вид в браузере:

Элементы нумерованного списка

Для выделения каждого элемента нумерованного списка используется HTML-элемент (сокр. от англ. list item – «элемент списка»). Закрывающий тег элемента является необязательным и может быть опущен, если за элементом непосредственно следует другой элемент или закрывающий тег . В открывающем теге элемента могут присутствовать универсальные атрибуты, атрибуты событий, а также собственный атрибут . (см. ).

Необязательный атрибут позволяет задать текущий порядковый номер элемента в списке. Единственное разрешённое значение этого атрибута — число, записанное арабскими цифрами, даже если список отображается с римскими цифрами или буквами. Элементы списка, которые идут после элемента с таким атрибутом, нумеруются, начиная с заданного значения.

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

<ol>
  <li>Первый элемент списка.</li>
  <li>Второй элемент списка.</li>
  <li>Третий элемент списка.</li>
</ol>
<p><i>Примечание:</i> Текст примечания к
  третьему пункту списка.</p>
<ol>
  <li value="4">Четвёртый элемент списка.</li>
  <li>Пятый элемент списка.</li>
  <li>Шестой элемент списка.</li>
</ol>

В браузере это будет выглядеть так:

Remove Default List Item Marker Styling

There are three CSS properties we can use in our code to remove aspects of default styling from a list: list-style-type, margin, and padding.

Setting list-style-type to None

If we don’t want any sort of bullet point or ordinal indicator (like a number or letter) before list items, we can set the list-style-type property to none. Here’s an example of using this property to remove any bullet point or ordinal indicators in a list:

styles.css

ul {
	list-style-type: none;
}

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 is still structured as a list, but when displayed on the web page, the list’s items lack markers.

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

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