Html href display block

take a look at stackoverflow.com/questions/796087/make-a-div-into-a-link, @thepeer has provided the best solution so far.

10 Answers 10

Make sure to use cursor:pointer for these DIVs

If you’re using HTML5, as pointed in this other question, you can put your div inside a :

Preffer this method as it makes clear in your structure that all the content is clickable, and where it’s pointing.

It will work fine but if you are more concern on the SEO purpose and performance these method is not that much good. Because According to semantic syntax we cannot put block level element into inline element. So Please let me know the correct answer.

@NadeemKhan Starting with HTML5, anchor can contain other elements. Check this other question, referring to the anchor changes in documentation: w3c.github.io/html-reference/a.html#a-changes

clearlydecoded.com/html-content-models Please go to the above link and read the error about putting block level element into inline element. I am dam sure that it would affect on SEO as well because according to content model these is not correct if you want to make good website then we have to take care of these thing. Are you agree with my points ?

I gave you the official HTML 5 documentation link, a StackOverflow explanation about it, telling you that your point is obsolete (it was valid in HTML4 days). Any good web crawler will just skip most of tags and parse links and the text content.

Читайте также:  Html section align center

If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.

Now when the user floats their cursor in that div the anchor tag will fill the div.

In Firefox 3.5 and IE8, I have to add «height: 100%;» to the anchor tag for it to take up the whole DIV height. Great alternative to the Javascript solutions.

So you want an element to be something it’s not?

Generally speaking this isn’t a good idea. If you need a link, use a link. Most of the time it’s easier to just use the appropriate markup where it belongs.

That all said, sometimes you just have to break the rules. Now, the question doesn’t have javascript, so I’m going to put the disclaimer here:

You can’t have a act as a link without either using a link (or equivalent, such as a that only contains a submit button) or using JavaScript.

From here on out, this answer is going to assume that JavaScript is allowed, and furthermore that jQuery is being used (for brevity of example).

With that all said, lets dig into what makes a link a link.

Links are generally elements that you click on so that they navigate you to a new document.

It seems simple enough. Listen for a click event and change the location:

Don’t do this

There you have it, the is now a link. Wait. what’s that? What about accessibility? Oh right, screen readers and users of assistive technology won’t be able to click on the link, especially if they’re only using the keyboard.

Fixing that’s pretty simple, let’s allow keyboard only users to focus the , and trigger the click event when they press Enter :

Don’t do this either

$('.link').on(< 'click': function () < window.location = 'http://example.com'; >, 'keydown': function (e) < if (e.which === 13) < $(this).trigger('click'); >> >);

Again, there you have it, this is now a link. Wait. again? Still accessibility problems? Oh ok, so it turns out that the assistive technology doesn’t know that the is a link yet, so even though you can get there via keyboard, users aren’t being told what to do with it.

Fortunately, there’s an attribute that can be used to override an HTML element’s default role, so that screen readers and the like know how to categorize customized elements, like our here. The attribute is of course the [role] attribute, and it nicely tells screen readers that our is a link:

Ugh, this is getting worse every minute

$('[role="link"]').on(< 'click': function () < window.location = 'http://example.com'; >, 'keydown': function (e) < if (e.which === 13) < $(this).trigger('click'); >> >);

Finally, our is a lin—oh now the other devs are complaining. What now?

Ok, so the devs don’t like the code. They tried to preventDefault on the event, and it just keeps working. That’s easy to fix:

I warned you this was bad

$(document).on( < 'click': function (e) < if (!e.isDefaultPrevented()) < window.location = 'http://example.com'; >>, 'keydown': function (e) < if (e.which === 13 && !e.isDefaultPrevented()) < $(this).trigger('click'); >> >, '[role="link"]'); $('[aria-disabled="true"]').on('click', function (e) < e.preventDefault(); >);
 
Fake Link
Fake disabled link

There we have it—THERE’S MORE? What else don’t I know? Tell me everything NOW so that I can fix it!

  • Ok, so there’s no way to specify target. We can fix that by updating to window.open .
  • Click events and keyboard events are ignoring Ctrl , Alt , and Shift keys. That’s easy enough, just need to check those values on the event object.
  • There’s no way to specify contextual data. Let’s just add some [data-*] attributes, and call it a day with that one.
  • The click event isn’t obeying the mouse button that’s being used, middle mouse should open in a new tab, right mouse shouldn’t be triggering the event. Easy enough, just add some more checks to the event listeners.
  • The styles look weird. WELL OF COURSE THE STYLES ARE WEIRD, IT’S A NOT AN ANCHOR!

well, I’ll address the first four issues, and NO MORE. I’ve had it with this stupid custom element garbage. I should have just used an element from the beginning.

Told you so

$(document).on( < 'click': function (e) < var target, href; if (!e.isDefaultPrevented() && (e.which === 1 || e.which === 2)) < target = $(this).data('target') || '_self'; href = $(this).data('href'); if (e.ctrlKey || e.shiftKey || e.which === 2) < target = '_blank'; //close enough >open(href, target); > >, 'keydown': function (e) < if (e.which === 13 && !e.isDefaultPrevented()) < $(this).trigger(< type: 'click', ctrlKey: e.ctrlKey, altKey: e.altKey, shiftKey: e.shiftKey >); > > >, '[role="link"]'); $('[aria-disabled="true"]').on('click', function (e) < e.preventDefault(); >);
 
Fake Link
Fake Link With Target
Fake disabled link

Note that stack snippets won’t open popup windows because of how they’re sandboxed.

That’s it. That’s the end of this rabbit hole. All of that craziness when you could have simply had:

The code I posted here probably has problems. It probably has bugs that even I don’t realize as of yet. Trying to duplicate what browsers give you for free is tough. There are so many nuances that are easy to overlook that it’s simply not worth trying to emulate it 99% of the time.

Источник

При этом надо помнить, что область ссылки ограничена размером текста. элемент блочный, он занимает всю ширину области просмотра, а ссылка строчная, её размер определяется размером содержимого. Так что щелчок не по тексту, а просто по этой строке ничего не даст. Для данного примера это может и не принципиально, а вот для какого-нибудь меню, где пункты меню визуально больше текста, важно. Поэтому мы модифицируем стиль ссылки, чтобы она занимала всё пространство внутри блока.

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

В более сложных и распространённых ситуациях блок представляет собой комбинацию заголовка, картинки и подписи к ней. Вспомните любой интернет-магазин с витриной товаров и вы поймёте, насколько популярны блоки, которые одновременно являются ссылками, ведь они должны вести на описание товара. Код HTML может быть примерно таким.

Таким образом, каждую часть нашего блока (картинку и название) мы оборачиваем одной и той же ссылкой и в стилях ставим ей свойство display со значением block . Тогда весь блок целиком визуально будет представлять собой одну ссылку, хотя на деле это набор ссылок.

Всё это относилось к HTML4, и на наше счастье в HTML5 ситуация поменялась. При этом, все описанные приёмы остались с нами, но и добавилось кое-что новое. Теперь мы можем внутрь ссылки вставлять блоки целиком. Вот как преобразуется наш код с учётом новых правил HTML5 и его новых элементов.

Код теперь выглядит нагляднее и проще.

Ещё на эту тему вы можете посмотреть видео, в котором раскрываются другие аспекты на тему ссылок и блоков.

Источник

Why do you put a display:block on an «a» tag that is inside a list?

I am just wondering what effect does display:block has on «a», I know that it is for the «a» tag since the link won’t work if I removed «a» and conversely if I removed «display:block», I’m just wondering why it should be «display:block».

2 Answers 2

To make the inline element (a, span etc) to behave like a box model element (div, p, h1 etc), in other words, to make the a tag behave like a div tag.

Inline elements can live side by side on the same line, for example if you write

they will appear like Link1 Link2 but box model elements can’t live in the same line, for example, if you write something like

Both divs will occupy the whole space around them (even if they are smaller in width). In a list, for example,

If the list width is 300px then the a tag will not cover the full width of the li’s width because by default the a tag is inline and using display:block will make the a element to occupy the full width of the li , even if it’s not that wide.

There are more to say about this, I’ve just gave you an example, you should read more. Check this link and also Check this example.

The w3schools explanation for display:block is as fallow

The element is displayed as a block-level element (like paragraphs and headers) and you can check the display behavior here

practically mostly we use display:block in four situations

  1. Element doesn’t contains any content, but need to show as fix size block. eg: link with background image but no text between open and close anchor tags.
  2. Element need to show in fix size ignore the auto size according to content.
  3. There are set of elements and each should display in each line (one element per line).
  4. To implement show hide we can use diaply:none and display:block

But link functionality doesn’t have any relationship with the display or CSS , link showld work interdependently, CSS wrote for the anchor tag, just for style the link.

Источник

enter image description here

I’m trying to construct CSS where the tag covers an entire block, so that anywhere on the can be clicked. Here’s how the final div should look (image is 64×64px): Here’s the HTML:

  
Html href display block

On The Beach Exclusive

Save 10% off all package holidays

7 Answers 7

May be you can write like this:

  Html href display block

On The Beach Exclusive

Save 10% off all package holidays

Note: as per html5 you can define block elements inside tag

If you want have to anchor cover the whole block, your HTML should reflect that. While block-level anchors are a fresh idea from XHTML2/HTML5, they are working in nearly all modern browsers (even IE 7).

Just enclose all the DIV’s contents with the anchor:

 
Html href display block

On The Beach Exclusive

Save 10% off all package holidays
div a

Shiny, but not new

What’s also very interesting about this technique is that actually this isn’t new: you can do it now. […] That’s one of the interesting things about HTML 5—it documents existing browser behaviour. As the browsers already handle wrapping links around block-level elements, and there is an obvious use-case, there was no reason to artificially keep the structure as invalid.

Источник

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