Внесение пользовательских изменений CSS на вашем сайте

:bookmark: Это руководство объясняет, как вносить изменения CSS на вашем сайте Discourse, включая введение в CSS, место для добавления CSS в Discourse и способы поиска правильных селекторов с помощью инструментов инспекции браузера.

:person_raising_hand: Требуемый уровень пользователя: Администратор

Краткое содержание

Это руководство охватывает:

  1. Краткое введение в CSS и ключевые концепции
  2. Как добавить CSS на ваш сайт Discourse с помощью компонентов тем
  3. Использование инструментов инспекции браузера для поиска правильных CSS-селекторов

Основы CSS

CSS означает каскадные таблицы стилей (Cascading Style Sheets). Вот три ключевых концепции, которые нужно понять:

  1. Структура: Правило CSS состоит из селектора, свойства и значения.
p {
  color: red;
}
  1. Каскад: Последнее примененное правило имеет приоритет. Например:
p {
  color: red;
}
p {
  color: green;
}

Параграфы будут зелеными, так как это последнее примененное правило.

  1. Специфичность: Более специфичные правила переопределяют менее специфичные. Например:
div p {
  color: green;
}
p {
  color: red;
}

Параграфы внутри div останутся зелеными, потому что div p более специфичен, чем p.

Добавление CSS на ваш сайт Discourse

Чтобы добавить CSS на ваш сайт Discourse:

  1. Перейдите в Внешний вид > Темы и компоненты из боковой панели навигации администратора и откройте вкладку Компоненты. (Или перейдите по этой ссылке для вашего сайта: https://yoursite.com/admin/config/customize/components)

  2. Нажмите Установить, затем :heavy_plus_sign: Создать новый

  3. Дайте имя вашему компоненту темы и нажмите Создать

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

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

  1. Нажмите Редактировать код

  2. Добавьте ваш CSS на вкладку CSS

  3. Нажмите “Сохранить”, чтобы применить изменения.

Поиск правильных CSS-селекторов

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

  1. Щелкните правой кнопкой мыши по элементу, который хотите изменить.

  2. Выберите “Просмотреть код” (Inspect) в контекстном меню.

  3. В панели инструментов разработчика найдите селекторы элемента.

  4. Щелкните соответствующие селекторы и добавьте ваше правило CSS.

  5. Скопируйте правило, вставьте его в раздел CSS вашего компонента темы и удалите конфликтующие правила.

Для более специфичных селекторов может потребоваться скопировать селектор, используемый в существующих стилях Discourse, и изменить его в вашем компоненте темы.

Вот видео, демонстрирующее описанные выше шаги:

Устранение неполадок

Если ваши изменения не применяются, убедитесь, что:

  • Компонент темы включен во всех соответствующих темах
  • Ваше правило CSS достаточно специфично, чтобы переопределить существующие стили

Дополнительные ресурсы

40 лайков
Policy notice: no basic HTML / CSS questions please
How can hide the 'Latest', 'Top', 'Badges' and 'Categories' in the hamburger menu?
Anyway to style discourse topic title? ( IE, red, bold, highlight, anything. )
Remove background color change after page loading
How to make pinned items have less text underneath them
Customising Login Page
How to disable all alert banners in discourse
Notification color: light blue
How do I change text color in my Header?
Customize posts' contents with your own styles
Toolbar under site header per category
How to hide 0 votes?
Change Default Badge Colors (Bronze, Silver, Gold)
🌐 www theme
Cloudfront cdn with discourse?
How to change search banner headline font size?
How to reduce the size of category logo image
Can I make a custom button with CSS and HTML?
Applying Scroll Bar (Horizontal & Vertical) to Code Snippets
Hide suspension status
How can I hide the add button from sidebar
Customizing FAQs and Guidelines
Forum homepage, how to make full screen?
Switching the discourse color scheme: Changing Red Hues in CSS
Selected Quote Background Color
How can i disable categories on home page?
How to remove bottom bar from all topics
Disable bio, location and profile picture
Prevent users from changing their Full Names
Is it possible to change via CSS the Category Moderator shield?
Line under avatar?
Custom CSS/HTML in non-default theme (without component)
Advanced Header Search
Edit or Disable "community" in sidebar menu
Can you change the color of customizable text?
Policy notice: no basic HTML / CSS questions please
How to resize 'Modern Category + Group Boxes' thumbnail via CSS
Category List with Banners
Customize Login pop-up box?
How do I disable the hot feature?
Search Banner image cuts off on smaller screens
"Reader Mode" theme component feedback
Finding CSS selectors for page layout, user groups
How to change the buttons' colors on hover?
How to remove Tos and privacy from ui?
How to add separator lines to the Welcome Banner sections?
Understanding link click counters
Watching category mandatory
Show Only Categories on Mobile View
Change URL or remove Powered by Discourse
Wishlist: visual cue for "user got a badge for this post"
Remove "pinned" button at bottom of topic
How to style category boxes?
vBulletin Emojis
Can We Represent Our Categories Like This on a Discourse Hosted Community
How to Edit the Menu Design and User Profile Design
Rounded login buttons
How can I make the home page similar to this one?
How do I add CSS?
Show sidebar to anonymous user + Welcome area in central theme
Remove search from the header
Replies and Views Orange Color, help!
Differentiate Admin and Moderator Shield Icons
Configuring the default sidebar for your users
How to use CSS for versatile-banner
Extra spaces within text
Turn off the “views” on topic
CSS edits not being applied on mobile
How to make login and registration pages look like this?
How do I move an image/banner to the VERY top of the page?
Theme Identification
How to customize the composer toolbar?
Which path or file handles the custom template CSS?
Homepage Feature
Help with locating the correct CSS location to change color of specific text
Daily Summary (1pm UTC)
Category description floating to the right
Top contributors sidebar Backgound
FKB Pro - Social theme
Which is Better? Discourse or Flarum?
Is there a way to link replies after they are posted?
Customize User Cards
Change hover background color for nav class buttons
Allow “Name" field to be disabled in registration dialog
How can discourse administrators turn off personal messages
How to change/remove icon on login screen?
Versatile Banner
Versatile Banner
Removing edit history pencil icon
Howto add a GAP between Categories
How can I add a menu item
Can't remove topic footer buttons on iOS
Support for Umami analytic
Hiding empty votes via plugin options
New default nav style and simplified color scheme
How can we either hide or grey out the upload icon in the Edit window? We have uploading disabled
Can the user avatars on the website and the content page of the post be hidden?
Removing category descriptions in main page, but retain them in individual category pages?
How to disable title changes for all users on Discourse?
Beginner's guide to using Discourse Themes
Trying to re-align an element of a theme and just wondering what it's called
Selected Quote Background Color
Differentiate contents from the topic list rows using different colors
Adjusting default composer height
Removing options from user activity action list
Understanding and managing post notices
Understanding and managing post notices
Is there a way to remove the pop-ups when making a new topic?
Looking for the perfect theme
Default category heading not hidden when category banner is used
Adding a table to your post using markdown
Search section like on Reddit?
Search section like on Reddit?
How to hide a button (SVG icon) if user is logged in?
Change the headings of preferences settings
How to change layout of login screen

Можно ли сделать это вики? Информация под заголовком «Где мне добавить мой CSS?» требует обновления, поскольку кнопки Изменить CSS/HTML больше нет, если вы установили существующую тему — что сейчас вероятно, если кто-то выбрал тему через новый Мастер настройки. Теперь мы просто используем компоненты темы, которые будут добавляться к существующим темам.

https://meta.discourse.org/t/make-css-changes-on-your-site/168101#where-do-i-add-my-css-5

Я могу обновить её, как только она станет вики.

10 лайков

Готово :+1:

5 лайков

Спасибо. Благодаря этой части я наконец получил желаемый ответ.

Мне требовался экземпляр Discourse для различных личных нужд, поэтому несколько дней назад я установил его на VPS.

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

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

.topic-list-item.visited a.title:not(.badge-notification),
.latest-topic-list-item.visited a.title:not(.badge-notification),
.category-topic-link.visited a.title:not(.badge-notification),
{
  color: #000000;
}

1 лайк