What is the proper way to display a logo with CSS?

2020-07-05 07:38发布

问题:

I've been learning CSS recently, and the tutorial series I'm watching says the best way to display a logo image is to wrap the text in an H1 tag, then set the CSS style for that tag to background image, with a text indent of -99999 or similarly large number.

This seems incredibly hackish and inelegant. It also seems like using CSS to hide text would be a big no-no for SEO purposes (as hiding text via CSS is frowned upon).

I've also read that using an img should be avoided, as the logo itself is not really content, so should be relegated to the design-side of the coding (i.e. CSS).

What is the current consensus on this?

回答1:

The correct way to display a Logo is with an <img> element. If you haven't studied logos and logotype, you might not realize that a logo has its own semantics and is required to be presented in a very specific manner. It may also have a required interpretation, which is what should be used in the [alt] attribute.

If that required interpretation is legitimately a heading in the page, it would be semantically correct to add it to a <h#> element:

<h1>
    <img src="logo.png" alt="Foo Co.: Where everyone can fizz the buzz" />
</h1>

Typically the logo is used as a link, so it's common to see:

<a href="/">
    <img src="logo.png"... />
</a>

Additionally the logo can be emphasized (could be either <strong> or <em> depending on degree):

<strong>
    <a href="/">
        <img src="logo.png" ... />
    </a>
</strong>

To understand the semantics of a logo. If you're referencing the Coca-cola company, the logo for the brand would not, and should not change if you swapped out, or removed a stylesheet. Most people understand that semantically,

is different from



回答2:

I always just wrap an anchor tag around an image:

<a href=""><img src=""></a>

or create the anchor tag as a block and set a background image

<a class="logo" href="">Logo</a>

.logo { 
         background: url("/path") no-repeat; 
         width: 100px; 
         height: 100px; 
         display: block; 
         text-indent: -9999px;
}


回答3:

You should always use img to display the logo. Using h1 and using the logo as background is a really bad practice and should be avoided. Your logo is the content and not a h1.

Harry Roberts has explained it clearly in his post - Your logo is an image, not a <h1>



回答4:

I think it doesn't really matter. There are many different ways of doing this, and they're all supported. They all work. Most of them are search engine-friendly and perfectly accessible.

I would do something like this:

<h1><a href="/"><img src="rsc/logo.jpg" alt="Frobozz Company"></a></h1>

Search engines, text-mode browsers and screen readers see the alt text, everyone else sees the logo image.