Valid css and xhtml

The Benefits of Validated XHTML & CSS Code

In my role as CommerceTuned UI lead, an essential part of the development process of our CSS/XHTML overhauls has been to validate all my CSS and XHTML code using the various W3C validation tools available. At first this was chiefly for debugging purposes – if the page looks strange then it could be as a result of mistakes in hand-coded XHTML or CSS – but the benefits of validation are by no means limited to aiding the website development process.

Search engines love to crawl semantic mark-up

Imagine search engine spider’s behaviour as like someone reading through the pages of a word document. A well-structured, validated xhtml page should be laid out with logical, ordered headings and paragraphs that describes the content to the ‘reader’, and therefore helps it to understand the information.

Conversely, imagine that due to invalid markup a misplaced tag tells the spider that a paragraph ends half-way through the content, or perhaps you may have by used a tag that is not part of the specified language of the document, thus the spider might not understand the context. Worse still, imagine you failed to correctly close a tag – this could mean that this portion of text gets skipped until the robot finds a closing tag. Validation helps to prevent all this from occurring.

Читайте также:  Using div with css

Your website will be forward-compatible

Code standards are always defined taking anticipated developments into account, so by definition valid code will ensure your website’s future is in safe hands. By taking shortcuts or ‘hacks’ that you know work for existing browsers (or other user-agents), you are running the risk that these same shortcuts may not work in later versions of the same device. In extreme circumstances you may need to re-write pages – or your entire website – to fix something that with a bit of forethought could have been easily avoided.

Validation and accessibility

Another positive from valid XHTML markup is that it will automatically pass some of the checkpoints that are covered in the ‘Single A’ level of the Web Content Accessibility Guidelines (WCAG). In the UK, passing all these checkpoints is a legal requirement as part of the Disability Discrimination Act 1995 (DDA).

For higher-level WCAG Guideline 3 also explicitly states that websites should Use markup and style sheets and do so properly, which implies validated code.

Validating for presentation

When is it OK to use invalid code?

On occasion, it may be difficult to achieve validity. Perhaps your website uses a CMS which generates its own invalid code through a ‘what-you-see-is-what-you-get’ text editor. It might be unrealistic cost-wise to address this problem. If this is the case, then you may want to investigate whether or not you can edit the HTML directly, and if so invest in basic HTML training for your website editor.

Or maybe you want to use a CSS style declaration that will not validate as it is from a newer specification (such as CSS3). As long as you understand that the declaration may not be widely supported, then there seems little point in dropping it just to achieve validity.

Читайте также:  Python read file with exception

Achieving validity

There are quite a few tools available to make the process of validation easier. Rather than having to visit a specific validation site, plug ins that work via the browser can make it very easy to check your code as you develop it. I’d recommend:

  • HTML validator (based on Tidy and OpenSP) [for the Mozilla Firefox browsers]. Gives you a quick-reference icon to indicate valid / invalid HTML / XHTML code.
  • Web Developer [for the Mozilla Firefox browsers] – Excellent CSS editing and validation features, including the ability to validate local CSS.
  • Microsoft Developer Toolbar [for Internet Explorer browsers] – similar in some respects to the Firefox toolbar above (but better to use the Firefox one if that is your browser of choice).

I personally can’t recommend any Mac developer tools as I mostly work on windows, but the Web Inspector for Safari might be worth a look.

Validation makes your life better

In summary, all these ‘pros’ for validation are for your benefit. It:

  • Helps you get traffic to your website through organic search results
  • Helps maintain and debug your code
  • Keeps your site up-to-date and consistent in presentation.

Initially, validating code may seem a like a bit of a pain but – as with any new approach to working – it gets easier and more natural the more you do it. And great fun too. OK, maybe not that.

Источник

Валидность HTML-кода

Валидность HTML-кода

Все мы с Вами знаем, что вольнее языка, чем HTML найти трудно. Однако, и у него существуют определённые правила, которые регулируются различными стандартами (HTML4, XHTML1.1 и другие). Но НЕсоблюдение этих стандартов не означает, что сайт не отобразится. Браузеры ВЫНУЖДЕНЫ отображать даже самый гнилой код. Если они будут отображать только валидный HTML, то примерно 95% сайтов пользователи просто не увидят, и браузер растеряет всю свою долю рынка. Ведь именно столько процентов сайтов не являются валидными вообще. О смысле и значении валидации я решил поговорить в этой статье.

Прежде чем приступать к разговору валидности, давайте с Вами определимся, что это такое. Скажу своими словами, валидный HTML-код — это HTML-код, написание которого соответствует стандарту, указанному в DOCTYPE. Например, у меня на сайте в DOCTYPE стоит XHTML1.1. Проверить валидность HTML-кода можно здесь: http://validator.w3.org — это официальный валидатор.

Так в чём же преимущества валидного кода:

  • Немного выше скорость загрузки.
  • Лёгкий парсинг сайта.
  • Лучшая индексация поисковыми системами, что следует из предыдущего пункта.
  • Более высокая кроссбраузерность.

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

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

А вот минус у валидации один — это потраченное время. Я добился валидности своего HTML-кода на сайте, причём добился на каждой странице, но стоило мне это 3 дня достаточно упорной работы.

Скажу честно, писать валидный код совсем необязательно. Но есть люди (такие как я), которые любят, чтобы всё было аккуратно, идеально, чтобы код был максимально чистым, даже если это и вовсе не требуется. И вот таких людей по статистике 5%, и именно столько сайтов являются валидными.

Я Вам более того скажу: на данный момент такие сайты как Google, Yandex, Mail, Rambler и другие гиганты не являются валидными и близко. В чём Вы можете убедиться, попытавшись проверить валидность их HTML-кода. Поэтому писать валидный код или невалидный — это не важно, главное, чтобы сайт был хороший.

Создано 26.02.2011 15:29:54

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

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

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 61 ):

    Здравстуйте Михаил. Скажите,существует ли программа по удалению лишних тегов? Или только через валидатор?

    Никаких программ не существует. А если и существует, то сомневаюсь, что они «хорошо удаляют». Валидатор служит лишь для проверки кода. Поэтому только вручную.

    А как узнать какие теги лишние?

    Те которые закрываются 2 раза, например, либо просто пустые ( ), которые при этом не несут никаких стилей на себе. А вообще, чтобы всё это подправить, нужно знать HTML и CSS.

    У вас код валидный, а вот ВКонтакте нет! http://validator.w3.org/check?uri=vk.com&charset=%28detect+automatically%29&doctype=Inline&group=0&user-agent=W3C_Validator%2F1.3

    Да, и ещё 99% сайтов невалидны, но это не означает, что это хорошо. А контакт — это пример низкокачественного сайта в плане реализации, поэтому и не стоит его в качестве примера приводить.

    Полностью согласен, Вконтакте даже нет страницы 404 и прочих хороших мелочей. В этом плане сайт очень-очень плох!

    На моей странице валидатор нашел непонятную мне ошибку: Line 10, Column 15: there is no attribute «HEIGHT» ✉ You have used the attribute named above in your document, but the document type you are using does not support that attribute for this element. This error is often caused by incorrect use of the «Strict» document type with a document that uses frames (e.g. you must use the «Transitional» document type to get the «target» attribute), or by using vendor proprietary extensions such as «marginheight» (this is usually fixed by using CSS to achieve the desired effect instead). This error may also result if the element itself is not supported in the document type you are using, as an undefined element will have no supported attributes; in this case, see the element-undefined error message for further information. How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case) and/or check that they are both allowed in the chosen document type, and/or use CSS instead of this attribute. If you received this error when using the element to incorporate flash media in a Web page, see the FAQ item on valid flash. Что это значит?

    Источник

    Valid CSS, XHTML logo generator

    I once knew a website where the user could generate the little W3C valid CSS tags which looked much nicer than the too large W3C official ones. It was also possible to fill the icons with whatever content and color for other stuff.

    I’ve lost the bookmark and wasn’t able to google it, can you post it and maybe other such resources?

    Can I modify the existing icons to create my own?

    No. The validator’s icons are distributed under the W3C document license, which allows distribution but does not allow derivative works.

    BUT I don’t care, cause I don’t want my design to look ****.

    You probably mean antipixel’s icons and LucaZappa’s Brilliant Button Maker.

    Picture of the icons http://img353.imageshack.us/img353/1368/stealthesebuttonsli4.gif

    From the antipixel website:

    If you want them, they’re yours , gratis, no strings attached.

    Pull them straight off the main page here if you want, and if you’d like to change anything about them, go ahead and do that. I’m posting the Photoshop files below so you can download those and change anything you want. You do not need to give me credit or provide a link back here or anything like that. (Some people are already using them and at least one kind soul has posted such a link back here. You don’t need to do that anymore, but thank you for being a more than decent person.)

    RSS buttons are also available.

    Here’s antipixel’s orginal badges:

    And this is the generator:

    Be careful though, W3C is strict about their logo usage (as is any company):
    W3C Logo and Icon Usage

    You don’t want your design to look amateurish? Then don’t put those logos on. The only people likely to care whether your site is valid are going to check whether they see the logo or not.

    Marker — CSS: Cascading Style Sheets, Only certain CSS properties can be used in a rule with ::marker as a selector: All font properties. The white-space property. color. text-combine-upright, unicode-bidi and direction properties. The content property. All animation and transition properties.

    CSS Styling Images

    Learn how to style images using CSS.

    Rounded Images

    Use the border-radius property to create Rounded Images :

    Источник

    Оцените статью