Html div and link

The first solution uses CSS absolution position, which is a bad practice most of the time. You can scroll down to see the other solution.

Create HTML

Create CSS

  • Set the position to «absolute» for the inner tag.
  • Use the z-index property to place the link above all the other elements in the div.
.container < font-size: 5em; background-color: #a8a8a8; color: white; width: 8em; height: 2em; line-height: 2; text-align: center; font-family: Helvetica, Arial, sans-serif; font-weight: bold; cursor: pointer; position: relative; > .link < position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: 1; >
HTML> html> head> style> .container < font-size: 5em; background-color: #a8a8a8; color: white; width: 8em; height: 2em; line-height: 2; text-align: center; font-family: Helvetica, Arial, sans-serif; font-weight: bold; cursor: pointer; position: relative; > .link < position: absolute; width: 100%; height: 100%; top: 0; left: 0; z-index: 1; > style> head> body> div class="container"> W3Docs a href="https://www.w3docs.com/"> span class="link"> span> a> div> body> html>

Result

You can also use the nested inside a hyperlink.

Second solution: making a div a clickable link by nesting it in the tag:

HTML> html> head> style> a < display: block; background: orange; padding: 20px; text-align: center; > style> head> body> a href="https://www.w3docs.com/learn-html/html-introduction.html"> div> This is a clickable div. div> a> body> html>

As the div takes place inside the anchor tag, the anchor tag covers all the div’s area, and thus the div becomes a clickable link.

Читайте также:  Php composer phar could not open

Источник

«Блочные» Сcылки в HTML5

Одной из новых и захватывающих вещей, которые можно реализовать в HTML5 является возможность оборачивания ссылками блочных элементов.

Представьте, что есть главная страница с множеством тизеров для новостной ленты, каждый из которых ведет на страницу с полным текстом статьи.

Очевидно, что каждая новость должна иметь заголовок, и наверняка появится желание также добавить иллюстрацию и сделать эти блоки кликабельными. Разметка, вероятно, будет выглядеть как-то так:

Bruce Lawson voted sexiest man on Earth

full story. A congress representing all the planet's women unanimously voted Bruce Lawson as sexiest man alive.

Read more

Обратите внимание, что есть три одинаковые ссылки (или две,как на сайте BBC News, если Вы решите, что ваши пользователи не нуждаются в ссылке «Читать далее»).

Код HTML5 будет таким:

 

Bruce Lawson voted sexiest man on Earth

gorgeous lovebundle. A congress representing all the planet's women unanimously voted Bruce Lawson as sexiest man alive.

Read more

Сейчас одна ссылка обрамляет весь тизер, убирая повторяющийся код, и создавая более широкую кликабельную область.

Отмечу также пару особенностей: во-первых, вам не нужно беспокоиться о том, что каждая ссылка “читать далее”ведет на другой ресурс (см. WCAG 2), потому что вся новость является ссылкой, поэтому весь текст ссылки уникальный. Во-вторых, обратите внимание, что я изменил альтернативный текст у изображения. В первом примере изображение является ссылкой, и я описал ее назначение, тогда как во втором примере текст содержит описание самого изображения — ”gorgeous lovebundle” — и тем самым дает больше информации пользователям.

Интересно, что на самом деле, эта техника не нова — вы можете использовать ее сейчас.

XHTML2 имел похожий механизм, который позволял использовать href с любым элементом, что Эрик Мэйер предложил использовать в HTML5, но, конечно, эта техника не является обратно совместимой . Одним из его альтернативных решений этой проблемы было изменение правил для тега а, и моя тестовая страница демонстрирует, что это работает на данный момент в любом браузере.

Еще одна интересная фишка в html5 — он документирует существующее поведение браузера. Так как браузеры уже поддерживают использование ссылок-контейнеров, и существуют очевидные варианты использования, нет смысла искуственно сохранять неверную структуру.

(Ирония: Эрик Мэйер использовал в качестве рабочего примера ссылку, включающую все яйчеки строки в таблице. Это не работает в HTML5; для этого понадобится скрипт.)

P.S. Это тоже может быть интересно:

Если вам понравилась статья, поделитесь ей!

Источник

putting the link in the div will only make the text a link and not the whole div.
the reason i’ve got the div in there is becuase i use it to create a box and add a colored background to this.

I also need to be able to achieve the same thing, with a list item.
e.g. I currently have

I need to make a whole div, become a link.

but this does not validate as xhtml strict.

putting the link in the div will only make the text a link and not the whole div.
the reason i’ve got the div in there is becuase i use it to create a box and add a colored background to this.

It doesn’t validate because it should be like this:

I don’t know where your learning from, but I would stop. Try here It’s a pretty good tutorial on HTML.

Oh, and w3schools.com is an excellent source for HTML, CSS, and PHP (IMHO), although I don’t think you need it.

A div cannot be made into a link. It is a structural element, and block level, and is not content by itself. is inline only and will not work on block level elements.

Can’t remember where i read it, it was a while back, so can’t remember if i’m doing it the right way.

The div that i have represents a small box on the screen, this box contains an image and a


tag and some text. The whole things needs to be a link.

i’m already using the javascript onclick method on the div, but i wanted to do it without using javascipt to make it more SEO friendly.

has anyone ever tried anything similar, or is there a better way of doing it, to acheive the same resutls.
Thanks

Can’t remember where i read it, it was a while back, so can’t remember if i’m doing it the right way.

The div that i have represents a small box on the screen, this box contains an image and a


tag and some text. The whole things needs to be a link.

i’m already using the javascript onclick method on the div, but i wanted to do it without using javascipt to make it more SEO friendly.

has anyone ever tried anything similar, or is there a better way of doing it, to acheive the same resutls.
Thanks

Depending on where your putting the text you can just make the image a link.

It can be done with javascript, like this:

In the syleheet add:
cursor: pointer;
to your div.

I didn’t know

had «onclick» as an attribute. Which makes me want to look further into making a div as a link. Just wrapping around a
will work but the validator complains about it.

I guess
display:block;
seems to do the trick.
technically it wouldn’t be a div as a link but same difference.

The book I’m reading suggests setting the display property of the anchor to block.

The div that i have represents a small box on the screen, this box contains an image and a


tag and some text. The whole things needs to be a link.

I believe there’s no point of inserting an image and


inside a link. A good alternative can be if you use display: block (as you already know), then use the image as a background-image with no-repeat, stuff a padding-left (or which ever side you want the image to be) according to the size of the image, and then finally replace the


with border-bottom.
If you want an encapsulating border for this whole thing, pack it inside a div tag (w3c’cally legal) with required border and a small padding.

One: The OP wants it to validate. CSS doesn’t cause HTML to validate. A block element cannot be placed in an inline element, regardless of the CSS. So, placing the DIV inside of the A won’t work.

Two: Part of the lack of validation is that the LI element should be the only direct child of the UL element. The A element cannot be the direct child of the UL element.

Three: ~jermouri has it right, to a point. However, giving the block element a «cursor:pointer» style doesn’t address the fact that clicking it will accomplish nothing.

So, the answer that you are looking for is to simply use an element other than DIV. For validation, you’ll want to use an inline element. You could use SPAN, as suggested by ~jermouri, or you could use an element with more meaning. I, personally, am more likely to choose STRONG, EM, B, or I before resorting to SPAN.

You can then use CSS to make these elements block elements. The reason that hte HTML must validate without the CSS is because the HTML should be able to stand on its own without the CSS. Without CSS, block elements inside of inline elements makes no sense.

Источник

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