Перейти к содержимому

Как сделать карточку в html

  • автор:

Простая семантичная карточка-ссылка

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

Первая реализация

Логично предположить, что этот элемент должен быть сделан тегом a . Как-то так:

 

Item header

Item looong description

Проблема

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

Во-вторых внутри карточки могут предполагаться другие ссылки. Например, на автора статьи или категорию товара:

 

Item header

Item looong description

Ivan Ivanovich

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

 

Item header

Item looong description

Ivan Ivanovich

Реализация получше

Все же стоит сделать карточку подходящим для нее тегом, в данном случае article , а главную ссылку положить в заголовок:

 

Item header

Item looong description

Теперь верстка семантична и будет нормально прочитана скринридерами, роботами и другими разработчиками.

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

 

Item header

Item looong description

article < position: relative; >h3 > a::before

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

«Вложенные» ссылки

Чтобы сделать внутри этой карточки ссылку на автора или категорию товара, положим нужные элементы поверх псевдо-элемента ссылки. Или же опустим псевдо под другие элементы. Значит нужно свойство z-index для управления контекстом наложения и pointer-events для управления событием клика.

 

Item header

Item looong description

Ivan Ivanovich
article < position: relative; z-index: 0; >h3 > a::before < position: absolute; content: ''; inset: 0; z-index: -1; >p, img
  • добавили z-index: -1 для псевдо-элемента, чтобы убрать его под все остальные элементы в карточке
  • добавили z-index: 0 для всей карточки, чтобы создать новый локальный контекст наложения, иначе бы псевдо был в глобальном контексте наложения и убрался под элемент body
  • добавили pointer-events: none; для описания и картинки, чтобы сделать их прозрачными для событий мыши, теперь клики в них считаются кликами в элемент ровно под ними, то есть в псевдо
  • элементы внутри карточки, которым мы не указали pointer-events (ссылка на автора в данном случае) будут лежать поверх псевдо и не пропускать через себя события мыши, это можно использовать для красивых ховер-эффектов

Более сложные ховер-эффекты

В примере выше по наведению мыши мы только меняем цвет текста для заголовка-ссылки. Это сделано с помощью псевдокласса :hover на теге a . Что делать, если по ховеру нам нужно менять цвет фона карточки?

Первая мысль: сделать селектор article:hover и в нем прописать новый цвет фона.

Почему это плохо? Bo-первых, потому что этот псевдокласс предназначен для интерактивных элементов. article не интерактивный. Во-вторых, этот эффект будет срабатывать, когда пользователь наводит мышку на «вложенные» ссылки. А должен только при наведении на «главную» ссылку.

Правильнее будет использовать функциональный псевдокласс :has() и написать так:

article:has(h3 > a:hover)

От такого решение нас пока останавливает только поддержка :has() в браузерах ��

Поэтому используем article:hover , но помним, что это не очень правильное решение.

Нерешенные проблемы

Это решение не идеальное с точки зрения UX. Например, нельзя выделить текст в карточке, не зажав кнопку Alt (option на MacOS). Эта проблема осталась нерешенной.

Цитирования

  • 324-ый выпуск подкаста Веб-стандарты
  • Фронтенд-новости №12 от Николая Шабалина

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

Мотивировать меня чаще писать о CSS можно на patreon.

Мои каналы о CSS css_mind и csswg_weekly в телеграм.

Нашли опечатку? Сообщите мне о ней.

Как сделать карточку автора

введите сюда описание изображения

Здраствуйте, мне нужно создать карточку автора типо слева обложка книги, а справа по очереди сверху вниз: Автор: Название: Рейтинг: Оценка: Отзыв: И внизу под этим всем Описание: И что бы это было обёрнуто в border(книга отдельно, и каждый из пунктов по отдельности) у меня так получилось

* < margin: 0; padding: 0; >body < background-color: #add8e6; font-size: 26px; height: 100vh; font-family: Tahoma; >.solid < width: 100%; height: 180px; background: #add8e6; position: absolute; top: -160px; transition: top 1s ease-in-out; border: 5px solid black; border-top: 0; display: table-cell; vertical-align: bottom; >.solid:hover < top: 0; >.solid p < text-align: center; margin: 50px; color: black; font-size: 39px; word-spacing: 46px; >.solid a < color: black; text-decoration: none; >.content < height: 100px; margin-top: 25px; >.content-color < width: 60%; background-color: white; margin: auto; >.book < border: 5px solid #1087af; width: 65%; height: 300px; border-radius: 19px; margin: 45px; >.book-text < float: right; padding-right: 5px; /*padding-left: 3px;*/ border-bottom: 10px solid #1087af; >.strelki < display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: space-between; align-content: flex-start; align-items: center; >.next-page < margin-top: 0%; margin-left: 0%; height: 50px; width: 50px; >.next-page1 < margin-top: 0%; margin-left: 95%; height: 50px; width: 50px; >.previous-page
    Book Reviews Mirokioo   

Главная Топ2 Топ1 Бонус

ТОП 3

Автор: Даниель КизНазвание: Цветы для Элджернона Рейтинг: 18+

Как сделать такую карточку товара? На чистом CSS

КарточкаКарточка товара Интересует сделать такую карточку товара, но не понимаю как именно это работает, также указываю ссылку на макет фигмы вот она Помогите пж кодом) У меня получилось сделать вертикальную зеленую карточку, но горизонтальную не выходит, и проблема с текстом внутри у меня, хелп ^_^

Отслеживать
sorochinskkydm
задан 20 янв 2021 в 15:49
sorochinskkydm sorochinskkydm
28 1 1 серебряный знак 6 6 бронзовых знаков

Вы сами что то делали? Обучение не входит в тематику stackoverflow, здесь помогают и даже делают иногда с ноля но когда вопрос интересный

20 янв 2021 в 15:57
В том то и дело что пытался, но не вышло, и зашел сюда попросить помощи.
20 янв 2021 в 18:45
флекс контейнер и два дива внутри, не?
20 янв 2021 в 19:55
Если пытались сами, то лучше приложите свою попытку.
20 янв 2021 в 21:55

2 ответа 2

Сортировка: Сброс на вариант по умолчанию

Задача типична, как говорится рутина

  1. смотрим размеры и устанавливаем шрифты и так же обнуляем отступы и главного документа
  2. Картинки — создаём рядом с index.html папку с именем img/images/i как угодно, если когда то у вас зайдёт речь о вёрстке под cms то там будет ограничение для имени этой папки и все картинки из figma складываем в эту папку

Я сделал просто так — использовал flexbox и для мануала покурите вот это : webref.ru и согласно инструкции на этом сайте мы укажем для родителя всех карточек: display: flex;

В общем смотрите и если вдруг что то станет не ясно — переспросите комментариями

Внимание — не адаптивно

javascript применил так как лень кучу раз писать src для картинок и так же кучу раз вставлять один и тот же текст —

Здесь чуть чуть модернизировал: codepen.io

let text = "Парикмахерское кресло НОРМ гидровлическое"; let price = "9900 ₽"; document.querySelectorAll(".description").forEach(function(el) < el.innerHTML = text; >); document.querySelectorAll(".price").forEach(function(el) < el.innerHTML = price; >); document.querySelectorAll("img").forEach(function(img) < img.src = "https://tua-vita.ru/upload/iblock/851/851fadff5982b69c94f3097c8630ada4.png"; >);
html, body < margin: 0; padding: 0; font-family: "Roboto", sans-serif; >.wrapper < text-align: center; background-color: #efefef; >.flex < display: inline-flex; padding: 20px 10px; >.cart < width: 180px; background-color: #fff; >.cart:not(:first-child) < margin-left: 20px; >img < display: inline-block; max-width: 150px; object-fit: cover; >.description < font-size: 14px; text-align: left; width: 90%; margin: 20px auto; >.price < margin: 20px auto; >.button < margin: 20px auto; >.button button < border: none; outline: none; display: inline-block; padding: 10px 20px; background: #66c05d; border-radius: 30px; transition: scale 0.1s ease-in; color: #fff; >.button:hover button
   

Карточки

Карточки Bootstrap предоставляют собой гибкий и расширяемый контейнер контента с несколькими вариантами и опциями.

О карточках

Карточка – это гибкий и расширяемый контейнер содержимого. Она включает опции заголовков и футеров, широкий спектр контента, контекстуальные цвета бэкграунда и мощные опции отображения. Если вы знакомы с Bootstrap 3, — карты заменили наши старые панели, «колодцы» (закругленная граница вокруг элемента с серой заливкой и паддингом) и маленькие версии изображений — «тамбнейлы». Схожая с этими элементами функциональность доступна для карточек в виде классов-модификаторов.

Пример

Карточки созданы с применением как можно более меньшего количества кода и стилей, но они все же имеют множество инструментов для настройки и контроля. Их легко выравнивать и сочетать с другими компонентами Bootstrap, т.к. они созданы с помощью «флексбокса». По умолчанию они не имеют margin , поэтому при необходимости используйте утилиты расстояния.

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

Placeholder

Название карточки

Some quick example text to build on the card title and make up the bulk of the card’s content.

 class="card" style="width: 18rem;">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.  href="#" class="btn btn-primary">Переход куда-нибудь  

Типы содержимого

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

Тело

«Фундамент» карточки – класс .card-body . Используйте его всегда, когда вам нужна выделенная секция внутри карточки.

This is some text within a card body.

 class="card">  class="card-body"> This is some text within a card body. 

Названия, текст и ссылки

Названия карточек создаются добавлением класса .card-title к тэгу . Аналогично, ссылки добавляются и размещаются рядом друг с другом добавлением класса .card-link в тэг .

«Подназвания» добавляются классом .card-subtitle в тэг . Если элементы с классами .card-title и .card-subtitle размещены в элементе с классом .card-body , название и «подназвание» карточки выровняются прекрасно.

Название карточки
Подзаголовок карты

Some quick example text to build on the card title and make up the bulk of the card’s content.

 class="card" style="width: 18rem;">  class="card-body">  class="card-title">Название карточки  class="card-subtitle mb-2 text-muted">Подзаголовок карты  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.  href="#" class="card-link">Ссылка карты  href="#" class="card-link">Другая ссылка  

Изображения

Класс .card-img-top размещает изображение наверху карточки. Текст может быть добавлен к карточке классом .card-text . Текст внутри этого класса может быть оформлен стандартными тегами HTML.

Placeholder

Some quick example text to build on the card title and make up the bulk of the card’s content.

 class="card" style="width: 18rem;">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.  

Списки

Создавайте списки содержимого в карточке с помощью «расширенных» списков.

  • Cras justo odio
  • Dapibus ac facilisis in
  • Vestibulum at eros
 class="card" style="width: 18rem;">  class="list-group list-group-flush">  class="list-group-item">Cras justo odio  class="list-group-item">Dapibus ac facilisis in  class="list-group-item">Vestibulum at eros  
  • Cras justo odio
  • Dapibus ac facilisis in
  • Vestibulum at eros
 class="card" style="width: 18rem;">  class="card-header"> Featured  class="list-group list-group-flush">  class="list-group-item">Cras justo odio  class="list-group-item">Dapibus ac facilisis in  class="list-group-item">Vestibulum at eros  

«Плавильный котел» (в смысле – бросайте все что есть)

Смешивайте и подгоняйте друг под друга разные типы содержимого в карточке. Показанный ниже пример включает стили для изображений, текста, групп списков – и все это обернуто в карточку фиксированной ширины.

Placeholder

Название карточки

Some quick example text to build on the card title and make up the bulk of the card’s content.

  • Cras justo odio
  • Dapibus ac facilisis in
  • Vestibulum at eros
 class="card" style="width: 18rem;">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.   class="list-group list-group-flush">  class="list-group-item">Cras justo odio  class="list-group-item">Dapibus ac facilisis in  class="list-group-item">Vestibulum at eros   class="card-body">  href="#" class="card-link">Card link  href="#" class="card-link">Another link  

Заголовок и «подвал»

Добавьте заголовок и\или подвал к карточке.

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

 class="card">  class="card-header"> Featured  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь  

Заголовки карточек можно стилизовать добавлением стиля .card-header к .

Featured
Специальный заголовок

With supporting text below as a natural lead-in to additional content.

 class="card">  class="card-header">Featured  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь  

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

Someone famous in Source Title

 class="card">  class="card-header"> Quote  class="card-body">  class="blockquote mb-0"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.  class="blockquote-footer">Someone famous in  title="Source Title">Source Title    
Специальный заголовок

With supporting text below as a natural lead-in to additional content.

2 days ago

 class="card text-center">  class="card-header"> Featured  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь   class="card-footer text-muted"> 2 days ago 

Размеры

У карточек нет определенной ширины width , так что они всегда будут занимать 100% ширины, пока не объявлено иное. Вы можете изменить ширины в CSS, классами сетки, SASS или утилити-классами.

Использование разметки сеток

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

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

 class="row">  class="col-sm-6">  class="card">  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь     class="col-sm-6">  class="card">  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь    

Утилиты

Используйте наши утилиты размеров для быстрой настройки ширины карточки.

Название карточки

With supporting text below as a natural lead-in to additional content.

Название карточки

With supporting text below as a natural lead-in to additional content.

 class="card w-75">  class="card-body">  class="card-title">Название карточки  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Кнопка    class="card w-50">  class="card-body">  class="card-title">Название карточки  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Кнопка  

Обычный CSS

Используйте обычный CSS для установки ширины.

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

 class="card" style="width: 18rem;">  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь  

Выравнивание текста

Вы можете быстро изменить выравнивание текста любой карточки – в ее частях или в целом – с помощью наших классов выравнивания.

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

 class="card" style="width: 18rem;">  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь    class="card text-center" style="width: 18rem;">  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь    class="card text-right" style="width: 18rem;">  class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь  

Навигация

Добавляйте элементы навигации в заголовок карточки (или блок) с компонентами навигации Bootstrap.

Специальный заголовок

With supporting text below as a natural lead-in to additional content.

 class="card text-center">  class="card-header">  class="nav nav-tabs card-header-tabs">  class="nav-item">  class="nav-link active" href="#">Active   class="nav-item">  class="nav-link" href="#">Link   class="nav-item">  class="nav-link disabled" href="#">Disabled     class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь  
Специальный заголовок

With supporting text below as a natural lead-in to additional content.

 class="card text-center">  class="card-header">  class="nav nav-pills card-header-pills">  class="nav-item">  class="nav-link active" href="#">Active   class="nav-item">  class="nav-link" href="#">Link   class="nav-item">  class="nav-link disabled" href="#">Disabled     class="card-body">  class="card-title">Специальный заголовок  class="card-text">With supporting text below as a natural lead-in to additional content.  href="#" class="btn btn-primary">Переход куда-нибудь  

Изображения

В карточках есть настройки для работы с изображениями. Вы можете добавить «уменьшенное изображение» к низу карточки, наложить содержимое карточки на изображение либо просто вставить его в карточку.

Маленькие изображения

По аналогии с заголовками и «подвалами», карточки могут иметь image cap вверху и внизу – маленькие изображения.

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

Placeholder

 class="card mb-3">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.  class="card-text"> class="text-muted">Last updated 3 mins ago

class="card"> class="card-body"> class="card-title">Название карточки class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. class="card-text"> class="text-muted">Last updated 3 mins ago

src=". " class="card-img-top" alt=". ">

«Наложение» изображений

Превратите изображение в фон карточки и наложите на него текст карточки. В зависимости от изображения тут могут потребоваться дополнительные стили или утилиты.

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

 class="card bg-dark text-white">  src=". " class="card-img" alt=". ">  class="card-img-overlay">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.  class="card-text">Last updated 3 mins ago  

Обратите внимание, что содержание не должно быть больше, чем высота изображения. Если содержимое больше изображения, оно будет отображаться за пределами изображения.

Горизонтальный

Используя комбинацию классов сетки и утилит, карты можно сделать горизонтальными для мобильных устройств и быстро реагировать. В приведенном ниже примере мы удаляем разводы сетки с помощью .no-gutters и используем классы .col-md-* , чтобы сделать карту горизонтальной в точке останова md . В зависимости от содержимого вашей карты могут потребоваться дополнительные настройки.

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

 class="card mb-3" style="max-width: 540px;">  class="row no-gutters">  class="col-md-4">  src=". " class="card-img" alt=". ">   class="col-md-8">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.  class="card-text"> class="text-muted">Last updated 3 mins ago

Стили карточек

У карточек есть множество опций для настройки их фона, границ и цвета.

Фон и цвет

Используйте утилиты фона и текста для изменения внешнего вида карточки.

Primary card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Secondary card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Success card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Danger card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Warning card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Info card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Light card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Dark card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

 class="card text-white bg-primary mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Primary card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card text-white bg-secondary mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Secondary card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card text-white bg-success mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Success card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card text-white bg-danger mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Danger card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card text-white bg-warning mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Warning card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card text-white bg-info mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Info card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card bg-light mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Light card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card text-white bg-dark mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Dark card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.  
Использование вспомогательных технологий

Использование цвета как дополнительного инструмента информативности доступно только в визуальной сфере, что ограничивает пользователей вспомогательных технологий, например, программ для чтения текста с экрана. Удостоверьтесь, что информация, обозначенная цветом, также доступна из самого контента (т.е. в тексте) или содержится в альтернативных средствах – таких как дополнительный скрытый в классе .sr-only текст.

Границы

Используйте утилиты границ для изменения атрибута border-color карточки. Заметьте, что вы можете вставить классы .text- в родительский элемент класса .card или в поднабор содержимого карточки – как показано ниже.

Primary card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Secondary card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Success card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Danger card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Warning card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Info card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Light card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

Dark card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

 class="card border-primary mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body text-primary">  class="card-title">Primary card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card border-secondary mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body text-secondary">  class="card-title">Secondary card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card border-success mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body text-success">  class="card-title">Success card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card border-danger mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body text-danger">  class="card-title">Danger card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card border-warning mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body text-warning">  class="card-title">Warning card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card border-info mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body text-info">  class="card-title">Info card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card border-light mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body">  class="card-title">Light card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.    class="card border-dark mb-3" style="max-width: 18rem;">  class="card-header">Header  class="card-body text-dark">  class="card-title">Dark card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.  

Утилиты миксинов

Вы также можете изменить границы заголовка карточки и «подвала», и даже удалить их background-color с помощью класса .bg-transparent .

Success card title

Some quick example text to build on the card title and make up the bulk of the card’s content.

 class="card border-success mb-3" style="max-width: 18rem;">  class="card-header bg-transparent border-success">Header  class="card-body text-success">  class="card-title">Success card title  class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.   class="card-footer bg-transparent border-success">Footer 

Расположение карточек

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

Группы карточек

Используйте их для отрисовки карточек как единого, прикрепленного элемента с колонками равной ширины и высоты. Группы карточек используют display: flex; для достижения таких свойств размеров.

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

Placeholder

Название карточки

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

 class="card-group">  class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.  class="card-text"> class="text-muted">Last updated 3 mins ago

class="card"> src=". " class="card-img-top" alt=". "> class="card-body"> class="card-title">Название карточки class="card-text">This card has supporting text below as a natural lead-in to additional content. class="card-text"> class="text-muted">Last updated 3 mins ago

class="card"> src=". " class="card-img-top" alt=". "> class="card-body"> class="card-title">Название карточки class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action. class="card-text"> class="text-muted">Last updated 3 mins ago

При использовании групп карточек с «подвалами» содержимое карточек расположится автоматически.

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago
Placeholder

Название карточки

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago
Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

 class="card-group">  class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.   class="card-footer">  class="text-muted">Last updated 3 mins ago    class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This card has supporting text below as a natural lead-in to additional content.   class="card-footer">  class="text-muted">Last updated 3 mins ago    class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.   class="card-footer">  class="text-muted">Last updated 3 mins ago   

«Карточный стол»

Нужен набор карточек равной ширины и высоты, не прикрепленных друг к другу? Используйте «карточный стол».

Placeholder

Название карточки

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago

Placeholder

Название карточки

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

 class="card-deck">  class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.  class="card-text"> class="text-muted">Last updated 3 mins ago

class="card"> src=". " class="card-img-top" alt=". "> class="card-body"> class="card-title">Название карточки class="card-text">This card has supporting text below as a natural lead-in to additional content. class="card-text"> class="text-muted">Last updated 3 mins ago

class="card"> src=". " class="card-img-top" alt=". "> class="card-body"> class="card-title">Название карточки class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action. class="card-text"> class="text-muted">Last updated 3 mins ago

Как и в группах карточек, подвалы карточек в «столах» автоматически расположатся в линию.

Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Last updated 3 mins ago
Placeholder

Название карточки

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago
Placeholder

Название карточки

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

 class="card-deck">  class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.   class="card-footer">  class="text-muted">Last updated 3 mins ago    class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This card has supporting text below as a natural lead-in to additional content.   class="card-footer">  class="text-muted">Last updated 3 mins ago    class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.   class="card-footer">  class="text-muted">Last updated 3 mins ago   

Колонки карточек

Карточки можно выстроить в Masonry-подобные колонки с помощью CSS, обернув их в .card-columns . Для облегчения выравнивания карточки созданы на основе column , а не на flexbox.

Внимание! Размеры карточек могут быть разными, поэтому положение колонок тоже может разниться. Чтобы карточки не выходили из колонок, задайте display: inline-block , т.к. column-break-inside: avoid не совсем рабочее решение.

Placeholder

Card title that wraps to a new line

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

Someone famous in Source Title

Placeholder

Название карточки

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat.

Someone famous in Source Title

Название карточки

This card has a regular title and short paragraphy of text below it.

Last updated 3 mins ago

Placeholder

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

Someone famous in Source Title

Название карточки

This is another card with title and supporting text below. This card has some additional content to make it slightly taller overall.

Last updated 3 mins ago

 class="card-columns">  class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Card title that wraps to a new line  class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.    class="card p-3">  class="blockquote mb-0 card-body"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.  class="blockquote-footer">  class="text-muted"> Someone famous in  title="Source Title">Source Title      class="card">  src=". " class="card-img-top" alt=". ">  class="card-body">  class="card-title">Название карточки  class="card-text">This card has supporting text below as a natural lead-in to additional content.  class="card-text"> class="text-muted">Last updated 3 mins ago

class="card bg-primary text-white text-center p-3"> class="blockquote mb-0"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat. class="blockquote-footer text-white"> Someone famous in title="Source Title">Source Title class="card text-center"> class="card-body"> class="card-title">Название карточки class="card-text">This card has a regular title and short paragraphy of text below it. class="card-text"> class="text-muted">Last updated 3 mins ago

class="card"> src=". " class="card-img-top" alt=". "> class="card p-3 text-right"> class="blockquote mb-0"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante. class="blockquote-footer"> class="text-muted"> Someone famous in title="Source Title">Source Title class="card"> class="card-body"> class="card-title">Название карточки class="card-text">This is another card with title and supporting text below. This card has some additional content to make it slightly taller overall. class="card-text"> class="text-muted">Last updated 3 mins ago

Колонки карточек также можно растянуть и настроить с помощью кода. Ниже показано расширение класса .card-columns с использованием такого же CSS, как мы использовали в колонках, — который создает набор отзывчивых ярусов для изменения числа колонок.

.card-columns  @include media-breakpoint-only(lg)  column-count: 4; > @include media-breakpoint-only(xl)  column-count: 5; > >

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *