简体   繁体   中英

Can you make a CSS <header> element into a link?

I have a site that has a <header> which is styled so that the header graphic is the background-image . I would like to have the header link to the home page.

Is there an elegant way to do this that will allow me to keep it as a header with a background-image ?

CSS:

#header {
  background-image: url('../images/header.jpg');
  height: 144px;
  display: block;
}

Background images are not linkable. The "proper" way to go about this would be to have an <a> element that has the appropriate href , and put the background-image to that. Use CSS to make the <a> tak up the needed space.

Your question refers to <header> element but the CSS code uses a class selector #header . Technically you could have <header class=header> , but that would be rather pointless, and #header suggests that the actual markup has <div class=header> .

Both a <header> element and a <div> element can be placed inside an <a> element, as far as actual browser behavior is considered. HTML specifications have traditionally disallowed such constructs, but HTML5 CR allows any “flow content” inside <a> .

If the header is really just one image (as a background image), then it would appear to be more natural to use just an a element and set the background image directly on it. However, this reduces accessibility, because there is no way to specify alternate text for a background image, so to screen readers and to browsers with image loading disabled, there would be a link with no content, no link text. Therefore, if the header should be a link, it is better to use a content image, eg

<header>
<a href="./"><img src=hdr.png alt="ACME Company" border=0></a>
</header>

(However, a content image forces the minimal page width to the width of the image. This is not always desirable, but that's a different story and different question.)

Anchors are now block elements in HTML5, so they can wrap block elements like h1 , p and div . They are not, however, meant to wrap header , article , nav , section etc.

You could use JavaScript to assign an onClick event to the header element if you do not have access to the markup or CSS, but that of course requires JavaScript in order to work.

Instead you will need wrap the contents of the header with an a and assign it a href to your homepage. You can then style the link (make sure you set it to display: block ) with a background image and other CSS.

I do it like this when using a separate style sheet.

Original css header tag

    <div id="header">

    </div>

Added span to make header a link

    <span><a href="http://www.yourwebsitename.com/">
    <div id="header">

    </div></a></span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM