I have been trying to validate my CSS, and the following lines continually return the error Parse Error [empty string]
.content { width:80%; text-align:center; margin-left:auto; margin-right:auto;
max-width:400px; border-width:4px; border-style:solid; border-color:#339900;
padding:5px; margin-top:10px; margin-bottom:10px; border-radius:20px;
background-color:#ccffcc; }
#side_link { position:fixed; bottom:5px; right:-4px;
background-image:url('img/FruitfulLogo.png'); height:29px; width:22px;
border-style:solid; border-width:2px; border-bottom-left-radius:5px;
border-top-left-radius:5px; border-color:#F90; background-color:#FF9; }
#side_link:hover { background-image:url('img/FruitfulLogo_over.png'); }
Am I missing something really obvious or really obscure?
Trott
64k22 gold badges166 silver badges206 bronze badges
asked Apr 29, 2011 at 20:22
5
You’re using css3 elements while this is still just a draft. The w3 validators aren’t yet equiped to deal with a lot of the new properties and attributes and they’ll spew out errors on perfectly valid css in some cases. This is one of them.
Just give them a year-or more- to patch things up. Until then, use your own judgement, css is relatively simple syntax wise.
answered Aug 15, 2011 at 23:26
sg3ssg3s
9,3513 gold badges35 silver badges52 bronze badges
2
As @BoltClock commented as well, this appears to be a validator bug.
Take out your border-radius items in .content and #side_link and it validates fine. As far as I can see, they are correct.
answered Apr 29, 2011 at 20:45
kjlkjl
9022 gold badges9 silver badges15 bronze badges
.content {
margin:10px auto;
padding:5px;
border:4px solid #390;
border-radius:20px;
width:80%;
max-width:400px;
background-color:#cfc;
text-align:center;
}
#side_link {
position:fixed;
bottom:5px;
right:-4px;
width:22px;
height:29px;
border:2px solid #F90;
border-radius:5px 0 5px 0;
background-color:#FF9;
background-image:url('img/FruitfulLogo.png');
}
#side_link:hover {
background-image:url('img/FruitfulLogo_over.png');
}
I’m going to concur that the validator is going nuts, because when I input the above, it shows the errors. But then you have to note that below the errors it outputs all of the above and says «all this stuff is valid.»
answered Apr 29, 2011 at 21:45
morewrymorewry
4,2003 gold badges33 silver badges35 bronze badges
I put it throught the W3C validator and this is what I got back.
3: .content — Property border-radius doesn’t exist in CSS level 2.1 but exists in : 20px 20px
7: #side_link — Property border-bottom-left-radius doesn’t exist in CSS level 2.1 but exists in : 5px 5px
8: #side_link — Property border-top-left-radius doesn’t exist in CSS level 2.1 but exists in : 5px 5px
When checking the CSS3 version it’s the same line numbers.
DarthJDG
16.5k11 gold badges48 silver badges55 bronze badges
answered Apr 29, 2011 at 20:25
SethSeth
6,2103 gold badges28 silver badges44 bronze badges
4
With a bit of help, you can always establish and eradicate a CSS parse error whenever it happens.
CSS provides a powerful way of styling websites, reducing web page load times, and saving precious time for developers. However, you need to know how to handle a CSS parse error. Read on to find out how.
Contents
- What Is a Parse Error in CSS?
- Ways to Minimize Cases of CSS Parse Error
- 1. Use frameworks
- 2. Seek simplicity
- 3. Structure your CSS file
- 4. Use advanced CSS
- Rules for Dealing With CSS Parsing Errors
- – Unknown Properties
- – Malformed declarations
- – Illegal values
- – At-Rules Without Known At-Keywords
- – Unexpected End of Style Sheet and String
- How to Fix a Parse Error in CSS
- – CSS Parse Error Handling
- Common CSS Errors Besides Parse Error
- – Forgotten details
- – Missed spellings
- – Multiple Choice
- – Wrong Selector
- Conclusion
What Is a Parse Error in CSS?
The parse error in CSS arises when the CSS parser detects something that does not comply with the requirements. Usually, a CSS parser demands CSS be written in a certain way.
CSS parser has specific requirements that include:
- Adding a semicolon at the end of all CSS properties
- One ruleset cannot contain the same CSS property twice
- All rules require both opening and closing curly brackets ({})
- All quotes should be closed
Ways to Minimize Cases of CSS Parse Error
There are ways of keeping your style sheets pristine for both your clients and designs. Having a clean CSS file makes it easy to implement your design ideas without delays. Below are some of the approaches you can use to avoid parsing errors in CSS.
1. Use frameworks
Like icons in the fashion industry set the tone for what is trending, trendsetters in tech influence the styling of thousands of websites. You may wonder how this happens. Well, developers build and publish frameworks which are a set of rules for the common website elements.
The frameworks offer you and other developers a good starting point for web design. They help you design a decent website fast. With a framework, you get a reliable base that you experiment with, like tweaking fonts and colors.
2. Seek simplicity
As the website grows, you will find yourself scrolling through a long list of CSS elements and rules. The rules may override each other in some cases, but eventually, the most specific rule will always win.
You may end up with more code than anticipated, especially when accounting for different screen sizes and browsers. So, it is good practice to always establish before including new style rules; perhaps the existing ones could work.
3. Structure your CSS file
You have various ways of refactoring your CSS code to ease use and navigation. Some of the most straightforward approaches are the most effective. These include:
- Uniform spacing between rules as well as in declarations across the CSS file to make it easy to read.
- Capitalize on semantic or familiar id/class names. For instance, avoid a class name such as “bottom_menu” instead use the semantic tag “footer.”
- Avoid repeating yourself. You should repeat as little code as possible. If some declaration is repeated across the file, consider typing it once and using various selectors.
- Test the CSS code using online tools that parse the file to highlight problem areas and show any parse error message. These tools are useful in pinpointing specific elements and experimenting with various styles.
4. Use advanced CSS
For someone with some programming skills, advanced CSS options like LESS or SASS are recommended. These let you take advantage of complex code options such as functions, nesting, and variables. The approach helps you clean your code and avoid parsing errors.
Rules for Dealing With CSS Parsing Errors
In most cases, a user agent ignores the illegal part of a style sheet. The user agent accomplishes this by parsing the illegal part to establish where it starts and ends. However, it acts as if the illegal part does not exist. User agents obey the following rules once they come across the scenarios below:
– Unknown Properties
The user agent should overlook a declaration with an unknown property. The user agent is going to consider only the part with known properties.
For example:
h1 { color: red; rotation: 70minutes}
The user agent will treat the style sheet as
– Malformed declarations
The user agents should be able to handle tokens they encounter as they parse declarations to the end. They must do this while correctly managing escapes and paying attention to rules on matching pairs of {}, [], (), ‘’, and “”. For instance, a malformed declaration may miss a property value, colon, or property name.
Failure to pair each properly will prompt a CSS parse error. In some cases, the user agent anticipates the beginning of a declaration or at-rule but finds an unexpected token. In such cases, the token is taken to be the first malformed declaration. That token is used to establish which tokens to overlook.
– Illegal values
The user agent should overlook a declaration containing an illegal value. A CSS parser will honor the first rule then ignore the rest. A user agent meeting CSS specifications can accept one or more rules.
– At-Rules Without Known At-Keywords
A user agent will ignore an invalid at-keyword alongside everything that follows it. It ignores everything until the end of the block with the invalid at-keyword or the next semicolon.
– Unexpected End of Style Sheet and String
A user agent should close all the open constructs at the end of the style sheet. These include parentheses, blocks, comments, strings, brackets, and rules. After reaching the end of a line, the user agent must close the string. Failure to terminate all the constructs properly throws a parse error message.
How to Fix a Parse Error in CSS
When you get parse errors as you copy CSS from a different source, you first need to check the final semicolon. The easiest way to fix these errors is to paste the CSS code into an editor like Notepad++. You can use the editor to find or replace these errors.
You can start by replacing all instances of a semicolon curly bracket with a curly bracket. Also, search for “;s” and replace it with “}}}” to avoid bothering with empty rules like {}. The search will show both ;} and ; }. You can then replace }}} with ;} to ensure your CSS rules have the right closing bracket.
To fix parse errors in CSS, review your custom CSS code. Look out for errors like a missing semicolon, curly brackets, or spelling mistakes in CSS properties. Usually, CSS parsing errors arise from one or several errors in custom CSS. After locating the issue in your custom CSS code, make the right changes, save and refresh to resolve the parse error message.
– CSS Parse Error Handling
CSS is resilient and tries very hard to accomplish what you want even when there is an error. Once it establishes an error in one line, it progresses to the next without any error. Sometimes, it is hard to confirm there is a parse error in your style sheet since the browser does not tell. That’s where online CSS validators come in to establish parsing errors in CSS code.
Common CSS Errors Besides Parse Error
No matter your experience, mistakes such as typos or an incorrectly closed tag in CSS are common. Below are the common errors in CSS.
– Forgotten details
With CSS, you can be as creative as possible, but there are some ground rules to follow. Each selector should be as a class or ID, provided it is not HTML TAG. The selector format should be appropriate with braces, property, value, colon, and semicolon.
If you miss one of the little details, strange things will happen, or the intended output will not be visible. CSS validators let you catch the little forgotten details.
– Missed spellings
Missed spelling errors are some of the most common errors in CSS and are easy to ignore. For instance, “left” is different from “left” in CSS and could be the difference between placing something on the right or the left side of your page.
– Multiple Choice
CSS will choose which one to use if the same selector has two references with conflicting information in your CSS code. It is common when you are adding your style sheet to another one. If nothing is happening for a specific selector, search the style sheet for another reference associated with the selector.
– Wrong Selector
Placing your wonderful designs inside the #content when they should be in #context-text will not help your layout. Fortunately, you can easily see these after viewing the page. So, you only need to cut and paste the code in the correct tag.
Conclusion
In this guide, we’ve covered various aspects of CSS parse errors. Here is a summary of what you need to handle these parsing errors:
Parse error in CSS occurs when a style sheet departs from the precise CSS parser requirements
- Common causes include missing a semicolon, curly brackets, or unknown properties
- With a bit of help from online CSS validators, you can easily catch and fix the error
- Check the line with the parse error and change the code accordingly
Parsing errors in CSS are common but are easy to fix when you know where to look. With this guide, you can indulge your creativity in CSS, knowing you can handle CSS parse errors thrown at you.
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
Разбор ошибок валидации сайта
Наконец-то появилось свободное время между бесконечной чередой заказов, и я решил заняться своим блогом. Попробуем его улучшить в плане валидации. Ниже в статье я расскажу, что такое валидация сайта, кода html и css, зачем она нужна и как привести сайт к стандартам на конкретном примере.
Что такое валидация сайта?
Простыми словами – это проверка на соответствие стандартам. Чтобы любой браузер мог отображать ваш сайт корректно. Большое влияние валидность сайта на продвижение не оказывает, но хуже точно не будет.
Конкретный пример прохождения валидации для страницы сайта
Возьмем первую попавшуюся страницу на моем сайте — Кодирование и декодирование base64 на Java 8. Забьем адрес страницы в валидатор и смотрим результат:
Errors found while checking this document as HTML 4.01 Transitional! Result: 105 Errors, 67 warning(s)
Да уж, картина вырисовывается неприятная: больше сотни ошибок и 67 предупреждений – как вообще поисковики индексируют мой блог, и заходят люди? Но не будем огорчаться, а научимся проходить валидацию, справлять ошибки. Итак, первое предупреждение:
Unable to Determine Parse Mode! The validator can process documents either as XML (for document types such as XHTML, SVG, etc.) or SGML (for HTML 4.01 and prior versions). For this document, the information available was not sufficient to determine the parsing mode unambiguously, because: the MIME Media Type (text/html) can be used for XML or SGML document types No known Document Type could be detected No XML declaration (e.g <?xml version="1.0"?>) could be found at the beginning of the document. No XML namespace (e.g <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">) could be found at the root of the document. As a default, the validator is falling back to SGML mode. Warning No DOCTYPE found! Checking with default HTML 4.01 Transitional Document Type. No DOCTYPE Declaration could be found or recognized in this document. This generally means that the document is not declaring its Document Type at the top. It can also mean that the DOCTYPE declaration contains a spelling error, or that it is not using the correct syntax. The document was checked using a default "fallback" Document Type Definition that closely resembles “HTML 4.01 Transitional”.
Это одно и тоже. А исправляется просто: в самом начале страницы добавить тег:
<!DOCTYPE html>
Проверяем ,что у нас получилось и видим, что одним этим тегом мы убрали 105 ошибок и 3 предупреждения! Теперь у нас осталось только 64 предупреждения. Начинаем разбирать их по одному.
Warning: The type attribute for the style element is not needed and should be omitted. From line 5, column 1; to line 5, column 23 /x-icon">↩<style type="text/css">↩↩↩↩A
Это значит, что для элемента style не нужен атрибут type – это лишнее. На странице у нас два таких замечания. Аналогичное предупреждение и по JavaScript:
Warning: The type attribute is unnecessary for JavaScript resources. From line 418, column 1; to line 418, column 31 </script>↩<script type="text/javascript">↩$(doc
Таких у нас 8 ошибок. Убираем данные атрибуты и ура – еще на 10 предупреждений меньше!
Error: CSS: background: The first argument to the linear-gradient function should be to top, not top. At line 39, column 61 0%,#E8E8E8 100%);↩ border-r
Следующая ошибка — первый аргумент у linear-gradient должен быть to top, а не top. Исправлем. Далее ошибка:
Error: CSS: Parse Error. From line 65, column 13; to line 65, column 16 margin: 0 auto;↩padd
Здесь у меня неверно закомментировано css. Надо просто убрать эту строку. Или закомментировать по-другому /* и */. Я так сделал, как привык так комментировать на Java.
Error: CSS: @import are not allowed after any valid statement other than @charset and @import.. At line 88, column 74 0,600,700,300);↩@import url(//
Теперь у нас идет ошибка импорта. Перенесем эти строчки в самое начало файла и она исчезнет.
Error: Bad value _blanck for attribute target on element a: Reserved keyword blanck used. From line 241, column 218; to line 241, column 295 cookies. <a href="//upread.ru/art.php?id=98" target="_blanck" style="display: inline;">Здесь
Далее не нравится значение атрибута target, нам сообщают, что надо использовать «blank» без нижнего подчеркивания спереди. Убираем.
Error: End tag li seen, but there were open elements. From line 379, column 2; to line 379, column 6 <ul>↩ </li>↩↩</ul
Теперь у нас идет div не на месте.
Error: Table columns in range 2…3 established by element td have no cells beginning in them. From line 262, column 5; to line 263, column 94 px;">↩<tr>↩<td colspan="3" style="width:100%; padding-bottom: 25px;padding-top: 0px; text-align:center;">↩<img
Следующая ошибка – лишний colspan у ячейки. В моем случае таблица состоит всего из одной ячейки, видимо, забыл убрать, когда менял дизайн. Теперь это и делаем.
Error: Element style not allowed as child of element div in this context. (Suppressing further errors from this subtree.) From line 486, column 1; to line 486, column 7 ↩</table>↩<tyle>↩.hleb Contexts in which element style may be used: Where metadata content is expected. In a noscript element that is a child of a head element. In the body, where flow content is expected. Content model for element div: If the element is a child of a dl element: one or more dt elements followed by one or more dd elements, optionally intermixed with script-supporting elements. If the element is not a child of a dl element: Flow content.
А эта ошибка говорит о том, что нельзя вставлять style внутри div. Переносим в начало файла.
Error: The width attribute on the table element is obsolete. Use CSS instead. From line 505, column 1; to line 505, column 21 >↩↩↩↩↩↩↩↩↩<table width ="100%">↩<tr>↩
Тут нам подсказывают, что не стоит устанавливать ширину атрибутом, а лучше сделать это отдельным тегом. Меняем на style=»width:100%;».
Error: Duplicate attribute style. At line 507, column 41 ign="top" style="padding-right
Переводим: дублируется атрибут style. Второй стиль при этом работать не будет. Объединяем
Error: Attribute name not allowed on element td at this point. From line 506, column 5; to line 507, column 82 0%;">↩<tr>↩<td style="width:1%;padding-right:10px;" valign="top" name="navigid" id="navigid">↩↩↩↩</ Attributes for element td: Global attributes colspan - Number of columns that the cell is to span rowspan - Number of rows that the cell is to span headers - The header cells for this cell
У ячейки не должно быть имени – атрибута name. Тут в принципе можно убрать, id вполне хватит.
Error: The valign attribute on the td element is obsolete. Use CSS instead. From line 506, column 5; to line 507, column 67 0%;">↩<tr>↩<td style="width:1%;padding-right:10px;" valign="top" id="navigid">↩↩↩↩</
Убираем valign. Вместо него ставим style=»vertical-align:top».
Error: & did not start a character reference. (& probably should have been escaped as &.) At line 543, column 232 при lineLength &t;= 0) и lineS
А эта ошибка вообще непонятно как оказалась ) Это я коде к статье ошибся. Меняем на <
Error: An img element must have an alt attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images. From line 654, column 1; to line 654, column 30 /><br />↩<img src="img/art374-1.jpg" />↩<br /
У изображений должен быть alt. Добавляем альты с описанием картинок.
Error: CSS: padding: only 0 can be a unit. You must put a unit after your number. From line 260, column 18; to line 260, column 19 dding: 10 20;↩}↩↩#
Только ноль может быть без обозначений. Надо поставить что – это пиксели, или к примеру, проценты. Добавляем px после чисел.
Warning: The document is not mappable to XML 1.0 due to two consecutive hyphens in a comment. At line 974, column 8 ipt> ↩↩↩ <!--детектим адблок
Не нравятся комментарии. Да, в общем, их можно и убрать, не разбираясь, не особенно они и нужны.
Error: Stray end tag td. From line 982, column 1; to line 982, column 5 ↩</table>↩</td>↩↩<sty
Заблудившийся тег td. Убираем его.
Error: Bad value for attribute action on element form: Must be non-empty. From line 1102, column 6; to line 1102, column 98 /h6>↩ <form action="" id="jaloba-to-me" class="submit" method="POST" accept-charset="windows-1251"> <tabl
Здесь валидатор не устраивает пустое значение атрибута action – должен быть адрес страницы какой-то. У нас обрабатывается данная форма js, так что без разницы, поставим action=”self”
Все! Смотрим результат:
Нет ошибок или предупреждений, страница полностью валидна.
Если вам что-то непонятно в статье или вы хотите, чтобы ваш сайт полностью соответствовал спецификации и стандартам HTML ,вы можете обратиться ко мне. Я проверю и устраню любые шибки валидации.
Автор этого материала — я — Пахолков Юрий. Я оказываю услуги по написанию программ на языках Java, C++, C# (а также консультирую по ним) и созданию сайтов. Работаю с сайтами на CMS OpenCart, WordPress, ModX и самописными. Кроме этого, работаю напрямую с JavaScript, PHP, CSS, HTML — то есть могу доработать ваш сайт или помочь с веб-программированием. Пишите сюда.
заметки, сайтостроение, html, валидация
A CSS definition for background-image could not be understood by the parser. Check its definition to ensure that it’s well formed and that it contains an appropriate value.
A CSS definition for an X property could not be understood by the parser. Check it to ensure that it’s well formed and that it contains an appropriate value.
The <table> element does not accept a height attribute. Use CSS instead.
The value on the display property is not valid.
The display CSS property sets whether an element is treated as a block or inline element and the layout used for its children, such as flow layout, grid or flex.
25,000 HTML checks per month. Fully automated.
Save time using our automated web checker. Let our crawler check your web pages on the W3C Validator.
The specified CSS filter is not a standard one, and may only work in some browsers.
font-display isn’t a CSS property, it’s a descriptor for use with the @font-face at-rule.
25,000 HTML checks per month. Fully automated.
Save time using our automated web checker. Let our crawler check your web pages on the W3C Validator.
This issue is a false positive by the W3C validator, fixed in the latest versions of Nu Validator.
The value revert is indeed a valid value for the CSS property font-size.
The @import CSS rule can be used to import a style sheet into another style sheet. It must appear at the top of the document, and after any @charset declaration.
The max-width CSS property sets the maximum width of an element. It prevents the used value of the width property from becoming larger than the value specified by max-width.
This property can express a value in different units like px, em, % or ch, and keyword values, but auto is not an allowed value.
Some examples of valid values for max-width:
/* <length> value */
max-width: 3.5em;
/* <percentage> value */
max-width: 75%;
/* Keyword values */
max-width: none;
max-width: max-content;
max-width: min-content;
max-width: fit-content(20em);
/* Global values */
max-width: inherit;
max-width: initial;
max-width: revert;
max-width: unset;
The value specified for the min-height CSS attribute is not valid.
Still checking your large sites one page at a time?
Save time using our automated web checker. Let our crawler check your web pages on the W3C Validator.
Содержание
- HTML Checking for Large Sites
- CSS: Parse Error.
- Related W3C validator issues
- Как проверить HTML валидацию сайта — основные ошибки
- Разделы блога
- Как проверить сайт на валидность HTML кода
- Заключение
- Сергей Моховиков
HTML Checking for Large Sites
Rocket Validator integrates the W3C Validator HTML checker into an automated web crawler.
CSS: Parse Error.
CSS styles could not be parsed, check the indicated line to find what caused the parser to fail. Common causes are unclosed curly brackets or comments, missing semicolons or unexpected or empty properties.
A CSS definition for background-image could not be understood by the parser. Check its definition to ensure that it’s well formed and that it contains an appropriate value.
A CSS definition for an X property could not be understood by the parser. Check it to ensure that it’s well formed and that it contains an appropriate value.
The element does not accept a height attribute. Use CSS instead.
The value on the display property is not valid.
The display CSS property sets whether an element is treated as a block or inline element and the layout used for its children, such as flow layout, grid or flex.
25,000 HTML checks per month. Fully automated.
Save time using our automated web checker. Let our crawler check your web pages on the W3C Validator.
The specified CSS filter is not a standard one, and may only work in some browsers.
font-display isn’t a CSS property, it’s a descriptor for use with the @font-face at-rule.
Still checking your large sites one page at a time?
Save time using our automated web checker. Let our crawler check your web pages on the W3C Validator.
This issue is a false positive by the W3C validator, fixed in the latest versions of Nu Validator.
The value revert is indeed a valid value for the CSS property font-size.
The @import CSS rule can be used to import a style sheet into another style sheet. It must appear at the top of the document, and after any @charset declaration.
The max-width CSS property sets the maximum width of an element. It prevents the used value of the width property from becoming larger than the value specified by max-width.
This property can express a value in different units like px, em, % or ch, and keyword values, but auto is not an allowed value.
Some examples of valid values for max-width:
The value specified for the min-height CSS attribute is not valid.
When was the last time you validated your whole site?
Keep your sites healthy checking for A11Y/HTML issues on an automated schedule.
Источник
Как проверить HTML валидацию сайта — основные ошибки
Разделы блога
Проверка валидности HTML кода сайта обязательно входит в мой технический аудит. Но не нужно переоценивать значимость ошибок валидации на SEO продвижение — она очень мала. По любой тематике в ТОП будут сайты с большим количеством таких ошибок и прекрасно себе живут.
НО! Отсутствие технических ошибок на сайте является фактором ранжирования, и поэтому пренебрегать такой возможностью не стоит. Лучше исправить, хуже точно не будет. Поисковики увидят ваши старания и дадут маленький плюсик в карму.
Как проверить сайт на валидность HTML кода
Проверяется валидация кода сайта с помощью онлайн сервиса W3C HTML Validator. Если есть ошибки, то сервис выдает вам список. Сейчас я разберу самые распространенные типы ошибок, которые я встречал на сайтах.
- Error: Duplicate ID min_value_62222
И за этой ошибкой такое предупреждение.
- Warning: The first occurrence of ID min_value_62222 was here
Это значит, что дублируется стилевой идентификатор ID, который по правилам валидности html должен быть уникальным. Вместо ID для повторяющихся объектов можно использовать CLASS.
Исправлять это желательно, но не очень критично. Если очень много таких ошибок, то лучше исправить.
Аналогично могут быть еще такие варианты:
- Error: Duplicate ID placeWorkTimes
- Error: Duplicate ID callbackCss-css
- Error: Duplicate ID Capa_1
Следующее очень распространенное предупреждение.
- Warning: The type attribute is unnecessary for JavaScript resources
Это очень частая ошибка при проверке валидации сайта. По правилам HTML5 атрибут type для тега script не нужен, это устаревший элемент.
Аналогично такое предупреждение для стилей:
- Warning: The type attribute for the style element is not needed and should be omitted
Исправлять эти предупреждения желательно, но не критично. При большом количестве лучше исправить.
- Warning: Consider avoiding viewport values that prevent users from resizing documents
Это предупреждение показывает, что нельзя увеличить размер страницы на мобильном или планшете. То есть пользователь захотел посмотреть поближе картинки или очень маленький текст и не может этого сделать.
Я считаю это предупреждение очень нежелательным, для пользователя неудобно, это минус к поведенческим. Устраняется удалением этих элементов — maximum-scale=1.0 и user-scalable=no.
- Error: The itemprop attribute was specified, but the element is not a property of any item
Это микроразметка, атрибут itemprop должен находиться внутри элемента с itemscope. Я считаю эту ошибку не критичной и можно оставлять как есть.
- Warning: Documents should not use about:legacy-compat, except if generated by legacy systems that can’t output the standard doctype
Строка about:legacy-compat нужна только для html-генераторов. Здесь нужно просто сделать но ошибка совсем не критичная.
- Error: Stray end tag source
Если посмотреть в коде самого сайта и найти этот элемент, видно, что одиночный тег прописан как парный — это не верно.
Соответственно, нужно убрать из кода закрывающий тег . Аналогично этой ошибке могут встречаться теги . Эту ошибку нужно исправлять.
- Error: An img element must have an alt attribute, except under certain conditions. For details, consult guidance on providing text alternatives for images
Все картинки должны иметь атрибут alt, я считаю эту ошибку критичной, ее нужно исправлять.
- Error: Element ol not allowed as child of element ul in this context. (Suppressing further errors from this subtree.)
Здесь не верно прописана вложенность тегов. В
- должны быть только
. В данном примере эти элементы вообще не нужны.
Аналогично могут быть еще такие ошибки:
- Element h2 not allowed as child of element ul in this context.
- Element a not allowed as child of element ul in this context.
- Element noindex not allowed as child of element li in this context.
- Element div not allowed as child of element ul in this context.
Это все нужно исправлять.
- Error: Attribute http-equiv not allowed on element meta at this point
Атрибут http-equiv не предназначен для элемента meta, нужно убрать его или заменить.
- Error: Attribute n2-lightbox not allowed on element a at this point.
- Error: Attribute asyncsrc not allowed on element script at this point.
- Error: Attribute price not allowed on element option at this point.
- Error: Attribute hashstring not allowed on element span at this point.
Здесь также нужно или убрать атрибуты n2-lightbox, asyncsrc, price, hashstring или заменить их на другие варианты.
- Error: Bad start tag in img in head
- Error: Bad start tag in div in head
Тегов img и div не должно быть в . Эту ошибку нужно исправлять.
- Error: CSS: Parse Error
В данном случае здесь не должно быть точки с запятой после скобки в стилях.
Ну такая ошибка, мелочь, но не приятно) Смотрите сами, нужно убирать это или нет, на продвижение сайта никакой совершенно роли не окажет.
- Warning: The charset attribute on the script element is obsolete
В скриптах уже не нужно прописывать кодировку, это устаревший элемент. Предупреждение не критичное, на ваше усмотрение.
- Error: Element script must not have attribute charset unless attribute src is also specified
В этой ошибке нужно убрать из скрипта атрибут charset=»uft-8″, так как он показывает кодировку вне скрипта. Я считаю, эту ошибку нужно исправлять.
- Warning: Empty heading
Здесь пустой заголовок h1. Нужно удалить теги
- Error: End tag br
Тег br одиночный, а сделан как будто закрывающий парный. Нужно убрать / из тега.
- Error: Named character reference was not terminated by a semicolon. (Or & should have been escaped as &.)
Это спецсимволы HTML, правильно нужно писать © или ©. Лучше эту ошибку исправить.
- Fatal Error: Cannot recover after last error. Any further errors will be ignored
Это серьезная ошибка:
После ничего вообще не должно быть, так как это последний закрывающий тег страницы. Нужно удалять все, что после него или переносить выше.
- Error: CSS: right: only 0 can be a unit. You must put a unit after your number
Нужно значение в px написать:
Вот аналогичная ошибка:
- Error: CSS: margin-top: only 0 can be a unit. You must put a unit after your number
- Error: Unclosed element a
— это парный тег, а здесь он не закрыт, соответственно, нужно закрыть. Ошибку исправлять.
- Error: Start tag a seen but an element of the same type was already open
- Error: End tag a violates nesting rules
Здесь отсутствие закрывающего тега нарушает правила вложенности, откуда идет уже фатальная ошибка.
- Fatal Error: Cannot recover after last error. Any further errors will be ignored
Это частный случай, так конечно нужно смотреть индивидуально.
- Warning: The bdi element is not supported in all browsers. Please be sure to test, and consider using a polyfill
Элемент bdi не поддерживается во всех браузерах, лучше использовать стили CSS, если нужно изменить направления вывода текста. Это не критичное предупреждение.
- Error: A document must not include both a meta element with an http-equiv attribute whose value is content-type, and a meta element with a charset attribute
Здесь 2 раза указана кодировка:
Нужно убрать в начале. Ошибку лучше исправить.
- Error: Bad value callto:+7 (473) 263-22-06 for attribute href on element a: Illegal character in scheme data: space is not allowed
Здесь запрещены пробелы для атрибута href, нужно писать так — callto:74732632206. Ошибку лучше исправить, но не критично.
- Error: CSS: max-width: Too many values or values are not recognized
И аналогичная ошибка:
- Error: CSS: max-height: Too many values or values are not recognized
В данных случаях для max-width: и max-height: не поддерживается свойство auto. Должно быть конкретное значение в px, % и других единицах измерения для CSS. В целом, эти ошибки не критичные.
- Error: The for attribute of the label element must refer to a non-hidden form control
Атрибут label должен относиться к фрагменту id с идентификатором «control-label». То есть нужно в код формы вставить кусок Тоже ошибка не критичная.
- Error: Legacy encoding windows-1251 used. Documents must use UTF-8
Кодировка windows-1251 уже устарела, сейчас везде используется utf-8. По хорошему нужно делать сайт изначально на utf-8, иначе он или отдельные страницы могут отображаться кракозябрами. Но это не критичная ошибка. Если у вас с сайтом все ок, то можно оставить, как есть.
Вот еще похожая ошибка:
- Error: Bad value text/html; charset=windows-1251 for attribute content on element meta: charset= must be followed by utf-8
Для атрибута content кодировка должна быть utf-8. Смотрите сами, хотите исправлять это или нет, не критично.
Заключение
После того, как сделана полная проверка, я составляю файл с грубыми ошибками и передаю его моим программистам или технической поддержке клиента. Кстати, почитайте интересную историю, как я искал себе программиста.
Итак, теперь вы знаете, как проверить валидацию сайта с помощью онлайн сервиса W3C HTML Validator, но как я сказал валидность кода далеко не самый важный фактор ранжирования, скорее всего после исправления ошибок вы не заметите существенной разницы в позициях или трафике сайта. Но я считаю, что все равно нужно привести сайт в порядок, и надеюсь, моя статья вам в этом помогла.
Сергей Моховиков
Здравствуйте! Я специалист по продвижению сайтов в поисковых системах Яндекс и Google. Веду свой блог и канал на YouTube, где рассказываю самые эффективные технологии раскрутки сайтов, которые применяю сам в своей работе.
Источник
I have a website assessment due next week and I need to fix this!
Here’s my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"> <!-- learnt this off code avengers,,, used to make every device undeerstand my page and show the correct size-->
<title> Learn Basic Maori </title>
<style>
body {
text-align: center;
color: white;
background-color: #B3733C;
background-image: url("images/swirl.png"); /* copied off w3schools and replaced with my image */
margin: auto;
font-size: large;
}
h1 {
text-shadow: 2px 2px 8px #212121 ;
}
img {
width: 250px;
}
This is the first couple lines of code, yes it does have an end tag, both the style html and head tag do. I can’t seem to fix it.
The error from the html validator reads » Parse Error. Style sheets should not include HTML syntax. . » and also I have a stray end tag which doesn’t show up on my html editor? I know for a fact it’s not there but the validator disagrees. Someone help!!!!
I am trying to validate a css file. Every one of my media queries is getting a parse error.
I have checked and I do not have any missing curly brackets, colons, or semi-colons.
I also set the W3C Validator to validate CSS 3.
Below is a sample of a media query that is getting a parse error:
@media and (min-width: 600px){
h1.page-titles{
font-size: 3.5em;
margin-top: 25px;
}
}
What can be the problem?
closetnoc
32.7k4 gold badges42 silver badges68 bronze badges
asked Apr 6, 2016 at 14:38
1
Here is a working example code from my own CSS.
@media screen and (max-width: 750px) {
.cont-left{
width: 85%;
}
}
You will notice the addition of the term screen.
answered Apr 6, 2016 at 14:57
closetnocclosetnoc
32.7k4 gold badges42 silver badges68 bronze badges
1