Lighthouse suggesting to fix my a href text
I have a html like that
<a href="https://twitter.com/@some-name-here" target="_blank" rel="noopener" class="social-icon twitter grayscale"></a>
What is really happens here is I just displaying the image inside a href by using css class:
.social-icon.twitter {
background: url('../images/logo-twitter.png') no-repeat center center;
}
I can’t do <a....>Twitter</a>
as in that case the displayed text will destroy the view.
I can’t think of anything else like just putting a span
with a text inside my a
and make it hidden e.g <a....><span class="hide">Twitter</span></a>
but wonder if there is any proper solution?
Any recommendations on that?
asked Aug 4, 2018 at 8:16
For accessibility reasons (required for screen readers) links must contain a text or have description in aria-label
attribute. In many use cases like yours you don’t want to add any text in a link, but instead use as image or any graphic element wrapper.
Fix it by adding aria-label="Twitter"
to your a
element, like
<a href="https://twitter.com/@some-name-here" aria-label="Twitter" target="_blank" rel="noopener" class="social-icon twitter grayscale"></a>
answered Aug 6, 2018 at 20:58
BinyaminBinyamin
7,31510 gold badges59 silver badges81 bronze badges
2
If want to implement this in react app then, We need to add aria-label property to <a>
tag.
Before:
<a href={`https://${ this.props.info }`} target="_blank" rel="noopener noreferrer">
<i className="fa fa-circle fa-stack-2x"></i>
<i className={ `fa fa-${ this.props.icon } fa-stack-1x fa-inverse` }></i>
</a>
After:
<a href={`https://${ this.props.info }`} aria-label={`${ this.props.name }`} target="_blank" rel="noopener noreferrer">
<i className="fa fa-circle fa-stack-2x"></i>
<i className={ `fa fa-${ this.props.icon } fa-stack-1x fa-inverse` }></i>
</a>
answered Oct 6, 2018 at 4:41
KARTHIKEYAN.AKARTHIKEYAN.A
16.7k6 gold badges115 silver badges130 bronze badges
For SlickNav
The solution is quite simple. Just add title to the element of the Javascript file which has aria-haspopup=»true» and tabindex=»0″ attribute. Add title like title=»Anything» in above-mentioned line. It will solve the problem.
Working example is Oceanspace
For other similar issues you have to add title attribute to the respective anchor element
answered May 20, 2021 at 14:20
У меня ошибка:
Links do not have a discernible name Link text (and alternate text for
images, when used as links) that is discernible, unique, and focusable
improves the navigation experience for screen reader users. Learn
more.
Я попытался включить aria-label, но это не сработало. Это вызывает ошибку:
<a href = "https://...../demo/index.php/Products/Description/Apple-Cinema-27/products_id-1" c = "Apple Cinema 27">
<img src = "images/products/130_61ajN-dgGxL._SL1000_.jpg"
alt = "Apple Cinema 27"
title = "Apple Cinema 27"
width = "130"
height = "130"
class = "media-object img-fluid">
</a>
Спасибо
Я потерялся в контексте ошибки, полагаю, что это простая утилита. Если да, то какой?
— stealththeninja
19.11.2018 05:29
@stealththeninja: Я предполагаю, что это Маяк. Ссылка «Узнать больше» указывает (или должна указывать) на developers.google.com/web/tools/lighthouse/audits/… Тем не менее, нигде не предлагается добавить метку aria, поэтому я скептически отношусь к тому, читали ли они документ.
— BoltClock
19.11.2018 05:41
Кажется странным, что альтернативный текст здесь не рассматривается — возможно, Lighthouse проявляет осторожность и предполагает, что не все AT увидят или объявят альтернативный текст изображения.
— BoltClock
19.11.2018 05:45
Опубликованный пример кода действителен и соответствует требованиям WCAG. Если вы получаете эту ошибку, чего-то еще не хватает. Для <a> не нужен видимый текст или aria-label, если есть вложенный <img> с атрибутом alt. Атрибут alt становится «доступным именем».
— slugolicious
19.11.2018 08:14
В чем разница между HTML4 и HTML5?
HTML4 и HTML5 — это версии HTML, стандартного языка разметки, используемого для создания веб-страниц. Некоторые из ключевых различий между HTML4 и…
Начала с розового дизайна
Pink Design — это система дизайна Appwrite с открытым исходным кодом для создания последовательных и многократно используемых пользовательских…
Учебник по Javascript
JavaScript — это язык программирования, который обычно используется для добавления интерактивности и других динамических функций на веб-сайты. Он…
Ответы
2
Возможно, атрибут alt нуждается в небольшой модификации. Атрибут alt должен определять назначение или цель ссылки. Вот очень упрощенный пример:
<a href = "contact.html">
<img src = "contact.png" alt = "Return to the contact page">
</a>
Следовательно, вам может не понадобиться атрибут aria-label.
Попробуйте использовать aria-label = «….» — это альтернативный текст для изображения.
<a
href = "https://...../demo/index.php/Products/Description/Apple-Cinema-27/products_id-1"
data-c = "Apple Cinema 27"
aria-label = "yourdescription">
Другие вопросы по теме
I have an error :
Links do not have a discernible name.
Error Links do not have a discernible name
<div id="kt-info-box_55b0dc-d7" class="wp-block-kadence-infobox"><a class="kt-blocks-info-box-link-wrap info-box-link kt-blocks-info-box-media-align-top kt-info-halign-center" href="https://albaytalraqy.com/%d8%b4%d8%b1%d9%83%d8%a9-%d9%86%d9%82%d9%84-%d8%a7%d8%ab%d8%a7%d8%ab/" aria-label="افضل شركة نقل اثاث وعفش بالرياض افضل شركة تخزين بالرياض"><div class="kt-blocks-info-box-media-container"><div class="kt-blocks-info-box-media kt-info-media-animate-none"><div class="kadence-info-box-icon-container kt-info-icon-animate-none"><div class="kadence-info-box-icon-inner-container"><span style="display:block;justify-content:center;align-items:center" class="kt-info-svg-icon kt-info-svg-icon-fe_truck"><svg style="display:inline-block;vertical-align:middle" viewbox="0 0 24 24" height="50" width="50" fill="none" stroke="currentColor" xmlns="http://www.w3.org/2000/svg" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><title>افضل خدمات نقل وتخزين الاثاث والعفش بالمملكة العربية السعودية</title><rect x="1" y="3" width="15" height="13"></rect><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"></polygon><circle cx="5.5" cy="18.5" r="2.5"></circle><circle cx="18.5" cy="18.5" r="2.5"></circle></svg></span></div></div></div></div><div class="kt-infobox-textcontent"><h2 class="kt-blocks-info-box-title">نقل وتخزين الأثاث</h2></div></a></div>
How do I get to solve this problem?
GrahamTheDev
21.9k2 gold badges26 silver badges58 bronze badges
asked Aug 18, 2021 at 20:54
2
This could be a false positive.
Your aria-label
provides accessible link text (and there is text within the anchor itself).
One suggestion is that you might not have set the page language in your HTML declaration correctly and so it is struggling with a right to left language as the aria-label
(I am assuming right to left, please excuse my ignorance!).
Try adding lang=(relevant language ISO code)
to the <html>
declaration and see if that fixes it if you haven’t already done so.
Another possibility is that this error can be shown if you have two links going to the same URL with the same link text, check that this isn’t the case.
If neither of the above are true then you can safely ignore this warning.
answered Aug 19, 2021 at 16:23
GrahamTheDevGrahamTheDev
21.9k2 gold badges26 silver badges58 bronze badges
I have an error :
Links do not have a discernible name.
Error Links do not have a discernible name
<div id="kt-info-box_55b0dc-d7" class="wp-block-kadence-infobox"><a class="kt-blocks-info-box-link-wrap info-box-link kt-blocks-info-box-media-align-top kt-info-halign-center" href="https://albaytalraqy.com/%d8%b4%d8%b1%d9%83%d8%a9-%d9%86%d9%82%d9%84-%d8%a7%d8%ab%d8%a7%d8%ab/" aria-label="افضل شركة نقل اثاث وعفش بالرياض افضل شركة تخزين بالرياض"><div class="kt-blocks-info-box-media-container"><div class="kt-blocks-info-box-media kt-info-media-animate-none"><div class="kadence-info-box-icon-container kt-info-icon-animate-none"><div class="kadence-info-box-icon-inner-container"><span style="display:block;justify-content:center;align-items:center" class="kt-info-svg-icon kt-info-svg-icon-fe_truck"><svg style="display:inline-block;vertical-align:middle" viewbox="0 0 24 24" height="50" width="50" fill="none" stroke="currentColor" xmlns="http://www.w3.org/2000/svg" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><title>افضل خدمات نقل وتخزين الاثاث والعفش بالمملكة العربية السعودية</title><rect x="1" y="3" width="15" height="13"></rect><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"></polygon><circle cx="5.5" cy="18.5" r="2.5"></circle><circle cx="18.5" cy="18.5" r="2.5"></circle></svg></span></div></div></div></div><div class="kt-infobox-textcontent"><h2 class="kt-blocks-info-box-title">نقل وتخزين الأثاث</h2></div></a></div>
How do I get to solve this problem?
GrahamTheDev
21.9k2 gold badges26 silver badges58 bronze badges
asked Aug 18, 2021 at 20:54
2
This could be a false positive.
Your aria-label
provides accessible link text (and there is text within the anchor itself).
One suggestion is that you might not have set the page language in your HTML declaration correctly and so it is struggling with a right to left language as the aria-label
(I am assuming right to left, please excuse my ignorance!).
Try adding lang=(relevant language ISO code)
to the <html>
declaration and see if that fixes it if you haven’t already done so.
Another possibility is that this error can be shown if you have two links going to the same URL with the same link text, check that this isn’t the case.
If neither of the above are true then you can safely ignore this warning.
answered Aug 19, 2021 at 16:23
GrahamTheDevGrahamTheDev
21.9k2 gold badges26 silver badges58 bronze badges
Viewing 6 replies — 1 through 6 (of 6 total)
Hi @samot80,
Pretty sure that this is the reason why you’re seeing these notices:
Link text (and alternate text for images, when used as links)
Your popular post thumbnails don’t have alternate text (or alt
) assigned to them. The attribute is empty, hence the accessibility issue.
Take this one for example:
<li>
<a href="https://www.tachido.mx/chicas-palidas/" target="_self">
<img src="https://www.tachido.mx/wp-content/uploads/wordpress-popular-posts/167633-featured-380x250.jpg" srcset="https://www.tachido.mx/wp-content/uploads/wordpress-popular-posts/167633-featured-380x250.jpg, https://www.tachido.mx/wp-content/uploads/wordpress-popular-posts/167633-featured-380x250@1.5x.jpg 1.5x" alt="" class="wpp-thumbnail wpp_featured wpp_cached_thumb" loading="lazy" width="380" height="250">
</a>
<a href="https://www.tachido.mx/chicas-palidas/" class="wpp-post-title" target="_self">Chicas pálidas</a>
</li>
(That’s the post at the top of the list).
You need to make sure that your images have their alt attribute filled with descriptive text when used with links, as the error message describes, so people with visual disabilities can “see” them.
See Edit Media for more details.
Is it possible, if the alt””, the plugin places the name of the post in the featured image? For example: Post name = that’s amazing. If featured image.alt=”” then alt”that’s amazing” Or something like that?
Hola @samot80,
Voy a asumir que hablas español porque el sitio web está en español también 😛
Mira, el plugin llena el atributo ALT
de la imagen de forma automática con la data que está en Biblioteca de Medios (Media > Biblioteca). Si el atributo de la imagen está vacío en la biblioteca pues naturalmente la imagen no tendrá ALT en el front-end.
Si tienes muchas imágenes en la biblioteca -y por el tipo de sitio web que tienes supongo que es así- llenar todos esos campos manualmente va a tomar mucho tiempo. Afortunadamente, el plugin provee un filtro que te puede ayudar con eso, wpp_thumbnail_alt_attribute. Y casualmente el ejemplo que está en la documentación hace exactamente lo que necesitas: asigna el título del post como atributo ALT para la imagen.
Si tienes alguna pregunta avísame.
… aunque releyendo tu último comentario quizás sea mejor cambiar el código a ésto:
/**
* Modifies WPP thumbnails' ALT attribute.
*
* @param string $alt_attribute
* @param int $post_id
* @return string
*/
function my_wpp_thumbnail_alt_attribute($alt_attribute, $post_id) {
// The ALT attribute is missing
if ( '' == $alt_attribute ) {
// Let's use the post title as ALT attribute
// for our thumbnail
$alt_attribute = get_post_field('post_title', $post_id);
}
return $alt_attribute;
}
add_filter('wpp_thumbnail_alt_attribute', 'my_wpp_thumbnail_alt_attribute', 10, 2);
Muchas gracias Héctor, como bien dices, son bastantes imágenes y complicado colocar ese atributo. Si fuera yo el único que subo contenido sería más fácil. Una última duda, el código se agrega en functions.php ?
Por cierto, el plugin es estupendo y llevo años utilizándolo.
Saludos
Una última duda, el código se agrega en functions.php ?
Sip, va en el archivo functions.php
de tu tema actual.
También puedes utilizar un plugin como Code Snippets para agregar ese código a tu sitio web sin tener que tocar functions.php.
Personalmente prefiero la primera opción pero no está de más tener otras alternativas.
Por cierto, el plugin es estupendo y llevo años utilizándolo.
¡Gracias por el cumplido!
Viewing 6 replies — 1 through 6 (of 6 total)