User agent stylesheet chrome что это
Я хотел бы изменить таблицу стилей агента пользователя Chrome. Я не ищу, как переопределить их с помощью CSS. Я хочу изменить значения по умолчанию и добавить несколько новых правил, которые помогут мне ускорить рабочий процесс и повысить удобство работы в Интернете.
Пожалуйста, также я не ищу расширение, которое сделало бы эту работу для меня.
Для Chrome v32 и ниже:
- В Google Chrome перейдите по URL-адресу about:version и запомните «путь к профилю».
- Найдите путь к профилю в вашем файловом браузере. Внутри папки вашего профиля откройте User StyleSheets папку. Внутри «User StyleSheets» должен быть файл с именем Custom.css , который по умолчанию пуст.
- Просто добавьте свои стили в Custom.css .
@ Ахмад, вы сказали, I would like to modify Chrome's user agent stylesheet. I am not looking for how to override them with CSS. I want to modify the default values но приняли ответ, который делает именно то, что вы не хотели: переопределить значения по умолчанию с помощью CSS. Если это то , что вы хотите (ред), то вы должны изменить свой вопрос (и не забудьте добавить !important в ваши стили пользователей). (Если вы действительно хотите изменить стили пользовательского агента программы, вам нужно загрузить исходный код Chromium, изменить его и скомпилировать свою собственную копию.)
@StevenLiekens, да, это единственное, что имеет смысл: то not looking to override with CSS , что он имел в виду на странице . Вот почему я предложил ему отредактировать вопрос для ясности, если он имел в виду это, поскольку пользовательская таблица стилей - CSS .
Да, Google решил вообще отказаться от пользовательских таблиц стилей, хотя они были неотъемлемой частью веб-браузеров практически с незапамятных времен (я начал использовать их в IE4 или 5). Их оправдание в том, что его используют немногие, так что если его уронить, это улучшит производительность, что является абсолютной НО по всем трем показателям). Я продолжал игнорировать его постоянно растущие проблемы, говоря, что оно все еще стоило того, потому что это было лучше, чем другие браузеры, но это больше не соответствует действительности. Я "Оути"! Это было хорошо 138 недель. Хороший Chrome: сентябрь 2008 - апрель 2011. ПОКОЙСЯ С МИРОМ.
I'm working on a web page in Google Chrome. It displays correctly with the following styles.
It is important to note that I didn't define these styles. In Chrome developer tools, it says user agent stylesheet in place of the CSS file name.
Now if I submit a form and some validation error occurs, I get the following stylesheet:
The font-size from these new styles is disturbing my design. Is there a way to force my stylesheets and if possible, completely overwrite Chrome's default stylesheet?
Note also that on Chrome (51) you get only those two table entries when you don't have a doctype declaration. Otherwise, you only get the second one.
Related post here. Understanding how user-agent (or browser) style sheet is different from user and author style sheets will help conceptualize things easily.
14 Answers 14
What are the target browsers? Different browsers set different default CSS rules. Try including a CSS reset, such as the meyerweb CSS reset or normalize.css, to remove those defaults. Google "CSS reset vs normalize" to see the differences.
I always reset/normalise my CSS before every project, that way you have an "almost" level field across browsers. I have never heard of a negative "side-affect" as such, I'm sure if you have a quick look on Google you will find that it is recommended.
Resetting styles can cause weird results with form fields, particularly around field borders or multi-part elements like type="file".
Even though reset/normalize might help, it doesn't really answer the question, of why the user agent stylesheet is changing? I have the same problem where on they UA styles become different for pre-rendered pages I use for SEO. Any ideas on why it changes?
If is missing in your HTML content you may experience that the browser gives preference to the "user agent stylesheet" over your custom stylesheet. Adding the doctype fixes this.
That's a great hint. You saved me some time of research. Worth noted that in my case I had that doctype declaration but I had a script before. It looks like the DOCTYPE must happen first thing in the page to enter into consideration.
@ChrisMorgan quoting from the specification to which you have linked: "DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications". In an ideal world DOCTYPE wouldn't be necessary. But to claim the answer is "just not true" is quite bold IMHO, especially considering the number of upvotes.
Regarding the concept “user agent style sheet”, consult section Cascade in the CSS 2.1 spec.
User agent style sheets are overridden by anything that you set in your own style sheet. They are just the rock bottom: in the absence of any style sheets provided by the page or by the user, the browser still has to render the content somehow, and the user agent style sheet just describes this.
So if you think you have a problem with a user agent style sheet, then you really have a problem with your markup, or your style sheet, or both (about which you wrote nothing).
@givanse, no, you see user agent style sheet effects when you don’t override them, and your sample markup is no exception. It will be parsed as one li element containing two ul elements with just text content; they are styled by user agent style sheet, but this styling can be overridden. (Whether the markup is invalid depends on context and on HTML version; but this does not affect styling.)
@givanse, that problem is not relevant to the question “what is a user style sheet”. If you think the problem is important, post it as a new question, with sufficient details. But the bullet in your jsfiddle is simple a bullet for the li element, and your style sheet does not override it.
In my situation, there was a CSS specifier problem, but this information about the User Agent was also helpful.
Marking the document as HTML5 by the proper doctype on the first line, solved my issue.
Can you please explain how exactly it is supposed to work? How HTML 5 is associated with undefined styles? I'll confirm but do you have any ready fiddle to confirm it?
A user agent style sheet is a ”default style sheet” provided by the browser (e.g., Chrome, Firefox, Edge, etc.) in order to present the page in a way that satisfies ”general presentation expectations.” For example, a default style sheet would provide base styles for things like font size, borders, and spacing between elements. It is common to employ a reset style sheet to deal with inconsistencies amongst browsers.
From the specification.
A user agent's default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language. ~ The Cascade.
For more information about user agents in general, see user agent.
Answering the question in title, what is the user agent stylesheet, the set of default styles in the browser: Here are some of them (and most relevant ones also in today's web):
Personal opinion: Don't fight with them. They have good default values, for example, in rtl/bidi cases and are consistent nowadays. Reset what you see irrelevant to you, not all of them at once.
Define the values that you don't want to be used from Chrome's user agent style in your own CSS content.
Some browsers use their own way to read .css files. So the right way to beat this: If you type the command line directly in the .html source code, this beats the .css file, in that way, you told the browser directly what to do and the browser is at position not to read the commands from the .css file. Remember that the commands writen in the .html file is stronger than the command in the .css.
I had the same problem as one of my 's had the margin set by the browser. It was quite annoying but then I figured out as most of the people said, it's a markup error.
I went back and checked my section and my CSS link was like below:
I included type in it and made it like below:
My problem was solved.
I just wanted to expand on the response from @BenM based on what I read here from Ire Aderinokun. Because the user-agent stylesheet provides helpful default styling, think twice before overriding it.
I had a dumb error where a button element didn't look right in Chrome. I had partially styled it because I didn't want it to look like a traditional button. However, I left out style elements like border, border-color, etc. So Chrome was stepping in to supply the parts that it thought I was missing.
The problem went away once I added styles like border: none , etc.
So if anyone else is having this problem, make sure you are explicitly overriding all the applicable default user-agent styles for an element if you notice it looks wonky, especially if you don't want to reset the user agent styles completely. It worked for me.
I'm working on a web page in Google Chrome. It displays correctly with the following styles.
It is important to note that I didn't define these styles. In Chrome developer tools, it says user agent stylesheet in place of the CSS file name.
Now if I submit a form and some validation error occurs, I get the following stylesheet:
The font-size from these new styles is disturbing my design. Is there a way to force my stylesheets and if possible, completely overwrite Chrome's default stylesheet?
Note also that on Chrome (51) you get only those two table entries when you don't have a doctype declaration. Otherwise, you only get the second one.
Related post here. Understanding how user-agent (or browser) style sheet is different from user and author style sheets will help conceptualize things easily.
14 Answers 14
What are the target browsers? Different browsers set different default CSS rules. Try including a CSS reset, such as the meyerweb CSS reset or normalize.css, to remove those defaults. Google "CSS reset vs normalize" to see the differences.
I always reset/normalise my CSS before every project, that way you have an "almost" level field across browsers. I have never heard of a negative "side-affect" as such, I'm sure if you have a quick look on Google you will find that it is recommended.
Resetting styles can cause weird results with form fields, particularly around field borders or multi-part elements like type="file".
Even though reset/normalize might help, it doesn't really answer the question, of why the user agent stylesheet is changing? I have the same problem where on they UA styles become different for pre-rendered pages I use for SEO. Any ideas on why it changes?
If is missing in your HTML content you may experience that the browser gives preference to the "user agent stylesheet" over your custom stylesheet. Adding the doctype fixes this.
That's a great hint. You saved me some time of research. Worth noted that in my case I had that doctype declaration but I had a script before. It looks like the DOCTYPE must happen first thing in the page to enter into consideration.
@ChrisMorgan quoting from the specification to which you have linked: "DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications". In an ideal world DOCTYPE wouldn't be necessary. But to claim the answer is "just not true" is quite bold IMHO, especially considering the number of upvotes.
Regarding the concept “user agent style sheet”, consult section Cascade in the CSS 2.1 spec.
User agent style sheets are overridden by anything that you set in your own style sheet. They are just the rock bottom: in the absence of any style sheets provided by the page or by the user, the browser still has to render the content somehow, and the user agent style sheet just describes this.
So if you think you have a problem with a user agent style sheet, then you really have a problem with your markup, or your style sheet, or both (about which you wrote nothing).
@givanse, no, you see user agent style sheet effects when you don’t override them, and your sample markup is no exception. It will be parsed as one li element containing two ul elements with just text content; they are styled by user agent style sheet, but this styling can be overridden. (Whether the markup is invalid depends on context and on HTML version; but this does not affect styling.)
@givanse, that problem is not relevant to the question “what is a user style sheet”. If you think the problem is important, post it as a new question, with sufficient details. But the bullet in your jsfiddle is simple a bullet for the li element, and your style sheet does not override it.
In my situation, there was a CSS specifier problem, but this information about the User Agent was also helpful.
Marking the document as HTML5 by the proper doctype on the first line, solved my issue.
Can you please explain how exactly it is supposed to work? How HTML 5 is associated with undefined styles? I'll confirm but do you have any ready fiddle to confirm it?
A user agent style sheet is a ”default style sheet” provided by the browser (e.g., Chrome, Firefox, Edge, etc.) in order to present the page in a way that satisfies ”general presentation expectations.” For example, a default style sheet would provide base styles for things like font size, borders, and spacing between elements. It is common to employ a reset style sheet to deal with inconsistencies amongst browsers.
From the specification.
A user agent's default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language. ~ The Cascade.
For more information about user agents in general, see user agent.
Answering the question in title, what is the user agent stylesheet, the set of default styles in the browser: Here are some of them (and most relevant ones also in today's web):
Personal opinion: Don't fight with them. They have good default values, for example, in rtl/bidi cases and are consistent nowadays. Reset what you see irrelevant to you, not all of them at once.
Define the values that you don't want to be used from Chrome's user agent style in your own CSS content.
Some browsers use their own way to read .css files. So the right way to beat this: If you type the command line directly in the .html source code, this beats the .css file, in that way, you told the browser directly what to do and the browser is at position not to read the commands from the .css file. Remember that the commands writen in the .html file is stronger than the command in the .css.
I had the same problem as one of my 's had the margin set by the browser. It was quite annoying but then I figured out as most of the people said, it's a markup error.
I went back and checked my section and my CSS link was like below:
I included type in it and made it like below:
My problem was solved.
I just wanted to expand on the response from @BenM based on what I read here from Ire Aderinokun. Because the user-agent stylesheet provides helpful default styling, think twice before overriding it.
I had a dumb error where a button element didn't look right in Chrome. I had partially styled it because I didn't want it to look like a traditional button. However, I left out style elements like border, border-color, etc. So Chrome was stepping in to supply the parts that it thought I was missing.
The problem went away once I added styles like border: none , etc.
So if anyone else is having this problem, make sure you are explicitly overriding all the applicable default user-agent styles for an element if you notice it looks wonky, especially if you don't want to reset the user agent styles completely. It worked for me.
09.07.18 CSS 6666
Современные браузеры содержат свои базовые стили CSS для многих элементов, это можно заметить, открыв консоль разработчика и наведя на любой элемент - в консоли отобразятся его стили, даже если Вы ничего не прописывали. Помечаются они обычно надписью «user agent stylesheet». Это и есть родные стили браузера, которые он применяет к элементам. Зачем нужно их сбрасывать и всегда ли следует это делать?
CSS позволяет задать нужное оформление любой странице, без него код на HTML выглядел бы уныло. Действительно, CSS практически полностью отвечает за внешнее оформление любого тега, ведь тег – это всего лишь кирпичик, стоит убрать у него стили, от него останется нативный каркас с функциональной составляющей. Зачем браузеры добавляют свои стили к элементам HTML? Как раз по это причине. Ведь если не будут добавлены базовые стили, на них страшно будет смотреть, пусть даже Вы и разработчик, всё содержимое попросту склеится и наедет друг на друга.
Производители браузеров стремятся составлять базовые стили CSS таким образом, чтобы элементы выглядели стандартизовано. Разные движки и производители стараются использовать одинаковые таблицы стилей, чтобы во всех браузерах не было колоссальных различий в оформлении тегов. Часто можно управлять некоторыми стилями прямо из настроек браузера, например, можно задать цвет ссылок. Это и есть базовые стили CSS браузера.
Итак, мы разобрались для чего браузер добавляет свои стили к элементам HTML. Но иногда нужно убрать стили браузера и применить свои. Это может понадобится для создания уникального оформления элементов, создания необычного дизайна. И тут базовые стили браузера могут помешать.
Как сбросить стили браузера, а точнее удалить их? Раньше часто можно было увидеть на многих сайтах подключение файлов reset.css, в которых содержались огромные перечисления элементов HTML, для которых перечислялись сбрасывающие свойства. Эти свойства по сути просто обнуляли отступы, дизайн и т.д. Но использование файла reset.css не самый лучший вариант, так как это подключение лишнего файла, а значит и замедление скорости загрузки сайта. Но это не все, на составление таких стилей придется потратить немало времени, а потом может выясниться, что этот файл только мешает и сбивает с толку при верстке.
Поэтому, в настоящее время нет необходимости составлять отдельные файлы для сброса стилей. При разработке достаточно смотреть в консоль разработчика и обнулять нужные свойства путем переопределения стилей – нужно просто задать свое свойство CSS для тега, предыдущее будет отменено. Для некоторых базовых тегов, можно в общем файле стилей Вашего сайта сделать сброс их основных свойств. Таким образом, сброс стилей браузера будет выполняться по необходимости, за счет применения стилей сайта.
Я работаю над веб-страницей в Google Chrome. Он отображается правильно со следующими стилями.
важно отметить, что я не определил эти стили. На Chrome dev tools, он говорит таблица стилей агента пользователя вместо имени файла CSS.
Теперь, если я отправляю форму и возникает ошибка проверки, я получаю следующую таблицу стилей:
на font-size из этих новых стилей нарушает мой дизайн. Есть ли способ чтобы заставить мои таблицы стилей и, если возможно, полностью перезаписать таблицу стилей Chrome по умолчанию?
Что такое целевой браузер? Разные браузеры устанавливают разные правила CSS по умолчанию. Попробуйте включить сброс.в CSS или нормализуется.в CSS (Google для одного или для" reset vs normalise", чтобы увидеть различия), чтобы удалить эти значения по умолчанию.
Что касается понятия "таблица стилей агента пользователя", обратитесь к разделу Каскад в спецификации CSS 2.1.
таблицы стилей агента пользователя переопределяются всем, что вы устанавливаете в своей собственной таблице стилей. Это просто дно: при отсутствии каких-либо таблиц стилей, предоставляемых страницей или пользователем, браузер все равно должен отображать контент как-то, и таблица стилей агента пользователя просто описывает это.
Так что если вы думаете, что у вас есть проблема с таблицей стилей агента пользователя, тогда у вас действительно есть проблема с вашей разметкой, или вашей таблицей стилей, или обоими (о которых вы ничего не писали).
Если отсутствует в вашем html вы можете столкнуться с тем, что браузер отдает предпочтение "таблице стилей агента пользователя" над пользовательской таблицей стилей. Добавление параметра "DOCTYPE" исправляет это.
пометка документа как HTML5 соответствующим doctype в первой строке решила мою проблему.
в основном, таблица стилей по умолчанию, предоставляемая браузером. Из спецификации.
таблица стилей агента пользователя по умолчанию должна представлять элементы языка документа таким образом, чтобы удовлетворять общим ожиданиям представления для языка документа. ~ Каскад.
Также см. Дополнительные сведения об агенте пользователя в целом.
определите значения, которые вы не хотите использовать из стиля агента пользователя Chrome в вашем собственном CSS.
некоторые браузеры используют свой собственный способ чтения .файл CSS. Так что правильный способ победить это: Если ввести командную строку непосредственно в поле .HTML исходный код, это бьет .css-файл, таким образом, Вы сказали браузеру напрямую, что делать, и браузер находится в положении, чтобы не читать команды из .файл CSS. Помните, что команды записываются в the .html-файл сильнее, чем команда в .стиль CSS.
каждый браузер предоставляет таблицу стилей по умолчанию, называемую таблицей стилей агента пользователя, в случае, если HTML-файл не указывает ее. Заданные стили переопределяют значения по умолчанию. Поскольку вы не указали значения для поля элемента таблицы, были применены стили по умолчанию
у меня была та же проблема, что и у одного из моих, была маржа, установленная браузером, это было довольно раздражающе, но затем я понял, как и большинство людей, его ошибка отметки.
Читайте также: