Сайт остановлен за нарушение
Если вы являетесь владельцем сайта, то о причинах вы можете узнать в запросе от центра поддержки.
Оплаченный период закончился
3 дня теста хостинга закончились
Для продления бесплатного тестового периода на 27 дней подтвердите телефон или оплатите услугу.
Тестовый период завершен
Чтобы включить сайт произведите оплату в личном кабинете или с помощью быстрой оплаты.
Сайт временно остановлен
Если вы являетесь владельцем сайта, то о причинах вы можете узнать в запросе от центра поддержки.
How to fix CSS not linking to your HTML document
When working with HTML and CSS, you may find that your CSS is not styling your HTML document even when you’ve added the CSS to your page.
Here are six fixes that you can try to make your CSS work on your HTML page
Make sure that you add the rel attribute to the link tag
When you add an external CSS file to your HTML document, you need to add the rel="stylesheet" attribute to the <link> tag to make it work.
If you omit the rel attribute from the <link> tag then the style won’t be applied to the page.
Make sure you have the correct path in the href attribute
If you have the CSS file in the same folder as the HTML document, then you can add the path to the CSS file directly as shown below:
If you add a / before the file name, the CSS won’t be applied:
When your CSS is one folder away, you need to specify the folder name inside the href attribute without the / as well.
This is wrong:
This is correct:
Make sure the CSS file name is correct
The name of the CSS file that you put inside the href attribute must match the actual name of the CSS file.
If you have a CSS name with spaces, then you need to include the spaces in a URL-safe format by replacing it with %20
For example, suppose the name of your CSS file is my style.css , then here’s the correct name inside the href attribute:
Because URL can’t contain spaces, it’s recommended that you replace all spaces in your CSS file with a hyphen — or an underscore _ so that my style.css becomes my-style.css or my_style.css .
Make sure the link tag is at the right place
The <link> tag that you used in your HTML file must be a direct child of the <head> tag as shown below:
If you put the <link> tag inside another valid header tag like <title> or <script> tag, then the CSS won’t work.
The following example is wrong:
The external style CAN be put inside the <body> tag, although it’s recommended to put it in the <head> tag to load the style before the page content.
The following example still works:
Make sure that all your style rules are correct
When you have an invalid CSS syntax inside your stylesheet, then the browser will ignore the invalid syntaxes and apply the valid ones.
For example, suppose you have the following CSS file:
Because browsers have no support for choco color name, the style rule for <h1> tags above will be ignored while the background-color property for the <body> tag will be applied.
Make sure that you are using the right syntax for your styling because invalid CSS syntax won’t generate an error message.
Invalidate the cache with a hard reload
Sometimes, you might have the CSS file linked correctly from your HTML file, but you don’t see the changes you make to the CSS file reflected on the web page.
This usually happens when the browser serves a cached version of your CSS file.
To invalidate the cache and serve the latest version of your CSS file, you can perform a hard reload on the browser.
The shortcut to perform a hard refresh might vary between browsers:
- For Edge, Chrome, and Firefox on Windows/ Linux, you need to press Shift + CTRL + R
- For Edge, Chrome, and Firefox on macOS, you need to press Shift + CMD + R
- For Safari, you need to empty caches with Option + CMD + E or click on the top menu Develop > Empty Caches
If you’re using Chrome, you can also select to empty the cache and perform a hard reload with the following steps:
- Open the Chrome DevTools by pressing Shift + CTRL + J on Windows/ Linux or Option + CMD + J on Mac.
- Right-click on the reload (refresh) icon and select the third option
The image below shows the Chrome Empty Cache and Hard Reload option you need to select:
With that, you should see the latest CSS changes reflected on your web page.
Alternatively, you can also invalidate the browser cache by using CSS versioning as explained here:
And those are the six fixes you can try to link your CSS file to your HTML document.
I hope this tutorial has helped you fix the issue
Level up your programming skills
I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!
report this ad
About
Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.
Free Code Snippets Book
Get my FREE code snippets Book to 10x your productivity here
report this ad
Не применяются css
Правки стилей сайта производятся очень часто. Бывает, что нужно немного изменить цвет, положение, размеры или оформление определенного элемента сайта. Сначала инспектором веб браузера необходимо проверить правильность написания самих css правил:
Надпись inspector-stylesheet говорит о том, что данное правило добавлено не в css файлах, а вручную через инспектор. Если через инспектор необходимые изменения внешнего вида корректируемого элемента были достигнуты, то далее необходимо эти изменения внести в файл стилей сайта.
Если неизвестно из какого файла берутся стили сайта, то это можно посмотреть в исходном коде страницы (в большинстве браузеров вызывается через ctrl+u):
Файлов со стилями может быть подключено несколько. Также могут присутствовать отдельные файлы плагинов, если таковые установлены на сайте. Ваша задача найти основной файл стилей, который отвечает за внешний вид основного шаблона сайта.
Далее необходимо внести изменения в css файл, обычно новые стили с соответствующими комментариями добавляются последними строками в файл.
Но иногда изменения стилей не применяются, это может происходить по нескольким причинам:
-
Изменения на самом деле применились,но результата не видно из-за не обновленного кеша веб браузера. Всегда после изменения стилей необходимо делать очистку кеша через ctrl+F5.
У меня на мобильном телефона в веб браузере chrome часто бывает такой глюк: даже после очистки кеша сайт отображается неправильно. Берешь телефон друга, открываешь на нем сайт — там изменения применены. А на твоем телефоне, даже после очистки истории — нет.Вообще для проверки изменения в стилях удобно использовать режим инкогнито, в нем браузер не сохраняет кешированные версии сайта у себя в памяти, а все время делает загрузку с веб сервера.
В свежих версиях данных плагинов такой проблемы нет, так как после изменения файла стилей плагин заново генерирует свой кеш.
HTML not loading CSS file
I am completely stumped as to why this doesn’t work. It seems the HTML file can’t load the CSS for some reason, even though both are in the same directory. Any idea what might be the problem?
The above doesn’t work. Adding the css inline in index.html works fine though
26 Answers 26
to your link tag
While this may no longer be necessary in modern browsers the HTML4 specification declared this a required attribute.
type = content-type [CI]
This attribute specifies the style sheet language of the element’s contents and overrides the default style sheet language. The style sheet language is specified as a content type (e.g., "text/css"). Authors must supply a value for this attribute; there is no default value for this attribute.
Check both files in the same directory and then try this
As per you said your both files are in same directory. 1. index.html and 2. style.css
I have copied your code and run it in my local machine its working fine there is no issues.
According to me your browser is not refreshing the file so you can refresh/reload the entire page by pressing CTRL + F5 in windows for mac CMD + R.
Try it if still getting problem then you can test it by using firebug tool for firefox.
For IE8 and Google Chrome you can check it by pressing F12 your developer tool will pop-up and you can see the Html and css.
Still you have any problem please comment so we can help you.
You have to add type=»text/css» you can also specify href=»./style.css» which the . specifies the current directory
I have struggled with this same problem (Ubuntu 16.04, Bluefish editor, FireFox, Google Chrome.
Solution: Clear browsing data in Chrome «Settings > Advanced Settings > Clear Browsing Data», In Firefox, «Open Menu image top right tool bar ‘Preferences’ > Advanced «, look for this image in the menu: Cached Web Content click the button «Clear Now». Browser’s cache the .css file and if it has not changed they usually won’t reload it. So when you change your .css file clear this web cache and it should work unless a problem exists in your .css file. Peace, Stan
Your css file should be defined as UTF-8. Put this in the first line of you css file.
With HTML5 all you need is the rel , not even the type .
<link href=»custom.css» rel=»stylesheet»></link>
Well I too had the exactly same question. And everything was okay with my CSS link. Why html was not loading the CSS file was due to its position (as in my case).
Well I had my custom CSS defined in the wrong place and that is why the webpage was not accessing it. Then I started to test and place the CSS link to different place and voila it worked for me.
I had read somewhere that we should place custom CSS right after Bootstrap CSS so I did but then it was not loading it. So I changed the position and it worked.
Hope this helps.
Also make sure your link tag’s media attribute has a valid value, in my case, I was using WordPress CMS and passed the boolean value true in the media field so it showed like that.
That’s why it was giving error. There are three main attributes on which the css style loading depends.