Improve Article
Save Article
Improve Article
Save Article
In this article, we will learn to set an image or icon as the <li> image. We need to set the size of the custom list image to make it attractive. So, we will also learn the different ways to resize the custom list image.
Syntax: In this article, we will use below CSS properties.
- background-image: We will add a custom image as a background image in the list items.
li::before { background-image: url("image_URL"); }
- background-size: It will be used to set the size of the background image.
li { background-size: 20px; }
Approach 1: First, we will set the list-icon as background-image and we can customize its size using the height and width property.
Example:
HTML
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
title
>List icon</
title
>
<
style
>
li {
list-style: none;
}
/* Set the list image as background image*/
li::before {
content: '';
display: inline-block;
margin-right: 10px;
/* Height of the list image*/
height: 10px;
/* Width of the list image*/
width: 10px;
background-image: url(
}
</
style
>
</
head
>
<
body
>
<
h1
style
=
"color:green;"
>
GeeksforGeeks
</
h1
>
<
ul
>
<
li
>Geeks</
li
>
<
li
>for</
li
>
<
li
>Geeks</
li
>
</
ul
>
</
body
>
</
html
>
Output:
In the above output image, users can see the difference between the size of the list-style-image when we set sizes 30px and 10px.
Approach 2: In this approach, we will set the image size by using the background-size property for the <li> element.
Example:
HTML
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
title
>List icon</
title
>
<
style
>
/* Set the size of the list image using
the background-size property. */
li {
list-style: none;
padding: 10px 30px;
background-image: url(
background-repeat: no-repeat;
background-position: left center;
background-size: 20px;
}
</
style
>
</
head
>
<
body
>
<
h1
style
=
"color:green;"
>
GeeksforGeeks
</
h1
>
<
ul
>
<
li
>Geeks</
li
>
<
li
>for</
li
>
<
li
>Geeks</
li
>
</
ul
>
</
body
>
</
html
>
Output:
Users can see the above output image for the background-size: 20px.
Approach 3: We set the separate custom image for every list item and add style to that image.
HTML
Output:
Users can see the above output after setup the custom image for every list item.
Earn income with your CSS skills
Sign up and we’ll send you the best freelance opportunities straight to
your inbox.
We’re building the largest self-service freelancing marketplace for people like you.
CSS list-style-image Property
Markers are the bullets on a list with items.
The list-style-image
property uses an image as marker.
The image marker displays as is, and cannot be resized.
Example
#
A list with list-style-image
set to a leaf icon.
- Vincent Van Gogh
- Henri Matisse
- Paul Gauguin
<ul style="list-style-image: url('/img/css/leaf_icon.jpg')">
<li>Vincent Van Gogh</li>
<li>Henri Matisse</li>
<li>Paul Gauguin</li>
</ul>
Syntax
list-style-image: none | url | initial | inherit;
Values
#
Value | Description |
---|---|
none |
Default. No image will display. The element uses the list-style-type property instead. |
url |
Image path or URL. |
initial |
Sets the value to its default value. |
inherit |
Inherits the value from its parent element. |
Did you know?
Image markers with background-image
Alternatively, a background image can also be used as marker.
This has the advantage that the iamges size is adjustable.
Here is an example:
- Vincent Van Gogh
- Henri Matisse
- Paul Gauguin
<style>
.style-resize > li::before {
content: '';
display: inline-block;
height: 50px;
width: 50px;
background-size: cover;
background-image: url('/img/css/sunflowers-sm.jpg');
background-repeat: no-repeat;
margin-right: 10px;
background-position: center center;
vertical-align: middle;
}
</style>
<ul class="style-resize" style="list-style-type: none">
<li>Vincent Van Gogh</li>
<li>Henri Matisse</li>
<li>Paul Gauguin</li>
</ul>
Browser support
This table shows when list-style-image
support started for each browser.
Chrome |
1.0 | Dec 2008 |
Firefox |
1.0 | Nov 2004 |
IE/Edge |
4.0 | Sep 1997 |
Opera |
7.0 | Jan 2003 |
Safari |
1.0 | Jun 2003 |
You may also like
- Our CSS list-style Property Reference
- Our CSS list-style-position Property Reference
- Our CSS list-style-type Property Reference
- Our CSS Lists Tutorial
Earn income with your CSS skills
Sign up and we’ll send you the best freelance opportunities straight to
your inbox.
We’re building the largest self-service freelancing marketplace for people like you.
- CSS Tutorial
- CSS Selectors
- CSS Borders
- CSS Flex
- CSS Grid
- CSS Tables
- CSS Length
- CSS Fonts
- CSS Animation
- CSS Hover
- CSS Images
- CSS Comments
Я пытаюсь установить собственные значки SVG с помощью CSS на <ul>
элементы списка. Пример:
<ul>
<li style="list-style-image: url('first.svg')">This is my first item</li>
<li style="list-style-image: url('second.svg')">And here's my second</li>
</ul>
Проблема в том, что изображения слишком большие и растягивают высоту строк. Я не хочу изменять размер изображения, потому что смысл использования SVG — масштабирование с разрешением. Есть ли способ установить размер изображения с помощью CSS без каких-либо background-image
взломать?
РЕДАКТИРОВАТЬ: Вот предварительный просмотр (большое изображение, намеренно выбранное для иллюстрации и драмы): http://jsfiddle.net/tWQ65/4/
И мой нынешний background-image
обходной путь, используя CSS3 background-size
: http://jsfiddle.net/kP375/1/
11 ответы
Я бы использовал:
li {
list-style: none;
}
li::before {
content: '';
display: inline-block;
height: y;
width: x;
background-image: url();
}
ответ дан 20 авг.
Я использую:
li {
margin: 0;
padding: 36px 0 36px 84px;
list-style: none;
background-image: url("../../images/checked_red.svg");
background-repeat: no-repeat;
background-position: left center;
background-size: 40px;
}
где background-size устанавливает размер фонового изображения.
ответ дан 13 окт ’16, 13:10
Вы можете увидеть, как механизмы компоновки определяют размеры изображений списков здесь: http://www.w3.org/wiki/CSS/Properties/list-style-image
Есть три способа обойти это, сохранив при этом преимущества CSS:
- Измените размер изображения.
- Вместо этого используйте фоновое изображение и заполнение (самый простой способ).
- Используйте SVG без определенного размера, используя
viewBox
который затем изменится на 1em при использовании в качествеlist-style-image
(Престижность Джереми).
ответ дан 23 окт ’13, 19:10
Возможно, вы захотите попробовать тег img вместо установки свойства list-style-image. Установка ширины и высоты с помощью css фактически обрезает изображение. Но если вы используете тег img, размер изображения будет изменен на значение ширины и высоты.
ответ дан 15 окт ’11, 08:10
Спасибо Крису за отправную точку, это улучшение, которое касается изменения размера используемых изображений, использование first-child просто указывает на то, что вы можете использовать различные значки в списке, чтобы предоставить вам полный контроль.
ul li:first-child:before {
content: '';
display: inline-block;
height: 25px;
width: 35px;
background-image: url('../images/Money.png');
background-size: contain;
background-repeat: no-repeat;
margin-left: -35px;
}
Кажется, это хорошо работает во всех современных браузерах, вам нужно будет убедиться, что ширина и отрицательный отступ слева имеют одинаковое значение, надеюсь, это поможет
ответ дан 20 авг.
Почти как читерство, я просто зашел в редактор изображений и уменьшил размер изображения вдвое. Для меня работает как оберег.
Создан 16 июля ’13, 10:07
Вот пример, с которым можно поиграть Встроенный SVG для маркера списка (браузеры 2020 г.)
list-style-image: url("data:image/svg+xml,
<svg width='50' height='50'
xmlns='http://www.w3.org/2000/svg'
viewBox='0 0 72 72'>
<rect width='100%' height='100%' fill='pink'/>
<path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3
l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30
m-54 24v-24h9v24z'/></svg>")
- Играйте с SVG
width
&height
установить размер - Играть с
M70 42
поставить руку - различное поведение в FireFox или Chromium!
- удалить
rect
li{
font-size:2em;
list-style-image: url("data:image/svg+xml,<svg width='3em' height='3em' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 72 72'><rect width='100%' height='100%' fill='pink'/><path d='M70 42a3 3 90 0 1 3 3a3 3 90 0 1-3 3h-12l-3 3l-6 15l-3 3h-12l-6-3v-21v-3l15-15a3 3 90 0 1 0 0c3 0 3 0 3 3l-6 12h30m-54 24v-24h9v24z'/></svg>");
}
span{
display:inline-block;
vertical-align:top;
margin-top:-10px;
margin-left:-5px;
}
<ul>
<li><span>Apples</span></li>
<li><span>Bananas</span></li>
<li>Oranges</li>
</ul>
ответ дан 25 авг.
.your_class li {
list-style-image: url('../images/image.svg');
}
.your_class li::marker {
font-size: 1.5rem; /* You can use px, but I think rem is more respecful */
}
ответ дан 20 авг.
Я сделал своего рода эмулятор терминала с Bootstrap
и Javascript
потому что мне нужна была динамика, чтобы легко добавлять новые элементы, и я поставил подсказку из Javascript
.
HTML
:
<div class="panel panel-default">
<div class="panel-heading">Comandos SQL ejecutados</div>
<div class="panel-body panel-terminal-body">
<ul id="ulCommand"></ul>
</div>
</div>
Javascript
:
function addCommand(command){
//Creating the li tag
var li = document.createElement('li');
//Creating the img tag
var prompt = document.createElement('img');
//Setting the image
prompt.setAttribute('src','./lib/custom/img/terminal-prompt-white.png');
//Setting the width (like the font)
prompt.setAttribute('width','15px');
//Setting height as auto
prompt.setAttribute('height','auto');
//Adding the prompt to the list item
li.appendChild(prompt);
//Creating a span tag to add the command
//li.appendChild('el comando'); por que no es un nodo
var span = document.createElement('span');
//Adding the text to the span tag
span.innerHTML = command;
//Adding the span to the list item
li.appendChild(span);
//At the end, adding the list item to the list (ul)
document.getElementById('ulCommand').appendChild(li);
}
CSS
:
.panel-terminal-body {
background-color: #423F3F;
color: #EDEDED;
padding-left: 50px;
padding-right: 50px;
padding-top: 15px;
padding-bottom: 15px;
height: 300px;
}
.panel-terminal-body ul {
list-style: none;
}
Надеюсь, это вам поможет.
ответ дан 09 окт ’16, 01:10
Я добился этого, поместив тег изображения перед li:
HTML
<img src="https://www.pinclipart.com/picdir/big/1-17498_plain-right-white-arrow-clip-art-at-clipart.png" class="listImage">
CSS
.listImage {
float:left;
margin:2px;
width:25px
}
.li {
margin-left:29px;
}
ответ дан 20 авг.
Это поздний ответ, но я помещаю его здесь для потомков
Вы можете отредактировать svg и установить его размер. Одна из причин, по которой мне нравится использовать svg, заключается в том, что вы можете редактировать его в текстовом редакторе.
Ниже приводится 3232 svg, размер которого я внутренне изменил, чтобы изначально отображалось как 1010 фото. он отлично работал, чтобы заменить изображение списка
<?xml version="1.0" ?><svg width="10" height="10" id="chevron-right" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"><path style="fill:#34a89b;" d="M12 1 L26 16 L12 31 L8 27 L18 16 L8 5 z"/></svg>
Затем я просто добавил следующее в свой css
* ul {
list-style: none;
list-style-image: url(../images/chevron-right.svg);
}
Компания list-style: none;
важен, так как предотвращает отображение изображения списка по умолчанию во время загрузки альтернативного изображения.
ответ дан 20 авг.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
html
css
or задайте свой вопрос.