Владелец html is on

How to Add an HTML Button that Acts Like a Link

There are several ways of creating an HTML button, that acts like a link (i.e., clicking on it the user is redirected to the specified URL). You can choose one of the following methods to add a link to the HTML button.

Add an inline onclick event

You can add an inline onclick event to the tag.

Example of adding an onclick event to the tag:

html> html> head> title>Title of the document title> head> body> button onclick="window.location.href='https://w3docs.com';"> Click Here button> body> html>

It is also possible to add an inline onclick event to the tag within the element.

Читайте также:  Java вывод времени строка

Example of adding an onclick event to the tag:

html> html> head> title>Title of the document title> head> body> form> input type="button" onclick="window.location.href='https://www.w3docs.com';" value="w3docs" /> form> body> html>

Use the action or formaction attribute.

Another way of creating a button that acts like a link is using the action or formaction attribute within the element.

Example of creating a button acting like a link with the action attribute:

html> html> head> title>Title of the document title> head> body> form action="https://www.w3docs.com/"> button type="submit">Click me button> form> body> html>

To open the link in a new tab, add target=»_blank» .

html> html> head> title>Title of the document title> head> body> form action="https://www.w3docs.com/" method="get" target="_blank"> button type="submit">Click me button> form> body> html>

Since there is no form and no data is submitted, this may be semantically incorrect. However, this markup is valid.

Example of creating a button acting like a link with the formaction attribute:

html> html> head> title>Title of the document title> head> body> form> button type="submit" formaction="https://www.w3docs.com">Click me button> form> body> html>

The formaction attribute is only used with buttons having type=»submit» . Since this attribute is HTML5-specific, its support in old browsers may be poor.

Add a link styled as a button with CSS properties. A href attribute is the required attribute of the tag. It specifies a link on the web page or a place on the same page where the user navigates after clicking on the link.

Читайте также:  Display list object java
html> html> head> title>Title of the document title> style> .button < background-color: #1c87c9; border: none; color: white; padding: 20px 34px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; cursor: pointer; > style> head> body> a href="https://www.w3docs.com/" class="button">Click Here a> body> html>

Let’s see one more example.

html> html> head> title>Title of the document title> style> .button < display: inline-block; padding: 10px 20px; text-align: center; text-decoration: none; color: #ffffff; background-color: #7aa8b7; border-radius: 6px; outline: none; transition: 0.3s; > .button:hover < background-color: #c2c7c7; > style> head> body> a class="button" href="https://www.w3docs.com/learn-html/html-button-tag.html">HTML button tag a> body> html>

How about the accessibility?

Let’s take accessibility into our account for the last example. Here are some improvements to make the code more accessible:

If the button contained an image, it would be important to provide an alt attribute to make the image accessible to screen readers. Since this button doesn’t have an image, we don’t need to worry about this.

Adding a label to the button will help users who rely on assistive technology understand the purpose of the button. We can do this by wrapping the button text in a element and adding an aria-label attribute to the button.

To improve visibility for users with low vision, we can increase the contrast between the text color and background color of the button. We can achieve this by making the background color darker or the text color lighter.

Adding a focus style to the button will help users who navigate using the keyboard to see which element is currently focused. We can add a simple border to the button to achieve this.

Here’s the updated code with these improvements:

html> html> head> title>Title of the document title> style> .button < display: inline-block; padding: 10px 20px; text-align: center; text-decoration: none; color: #ffffff; background-color: #3c5d6e; border-radius: 6px; outline: none; transition: 0.3s; border: 2px solid transparent; > .button:hover, .button:focus < background-color: #c2c7c7; border-color: #7aa8b7; > style> head> body> a class="button" href="https://www.w3docs.com/learn-html/html-button-tag.html" aria-label="Learn about the HTML button tag">span>HTML button tag span> a> body> html>

Источник

CSS псевдокласс :is() — как и где его использовать

CSS псевдокласс :is() — как и где его использовать

Новый CSS псевдокласс :is() — это отличный способ выбирать нужные элементы, при этом не писать много лишнего кода, сохранять код читабельным. По сути :is() — следующая ступень эволюции псевдоклассов :matches() и :any(). Давайте начнем с того, что рассмотрим как работает этот селектор и как он заменяет оба :matches() и :any().

псевдокласс :is()

Пример использования :is()

Вероятно, можно интуитивно понять что делает :is() просто посмотрев на него. По сути это средство проверки является ли элемент чем-либо. Как if в языках программирования. Посмотрите на примеры ниже, функционально оба этих селектора одинаковы.

В обоих случаях стили будут работать, если элемент является div-ом.

Псевдокласс также можно использовать для выбора нескольких элементов в одном объявлении через запятую. Опять же, два селектора в примерах ниже функционально одинаковы.

Да, по началу это может показаться не очень полезным, пока видны только дополнительные сложности с синтаксисом. :is() становится особенно полезным, когда вам нужно выбрать дочерние элементы. Предположим, вы хотите, чтобы все заголовки h1 были написаны жирным шрифтом, но только в том случае, если они являются дочерними элементами тегов article , section или aside . Для этого вам нужно написать:

 CSS article h1, section h1, aside h1 { font-weight: bold; } 

Но используя :is() можно сжать селектор до такого вида:

 CSS :is(article, section, aside) h1 { font-weight: bold; } 

Эффективность использования псевдокласса :is() увеличивается, если у вас есть несколько родительских и дочерних элементов. А что если вы захотите, чтобы жирным шрифтом были написаны не только заголовки h1, а вообще все заголовки? Без :is() вам нужно будет написать следующее:

 CSS article h1, article h2, article h3, article h4, article h5, article h6, section h1, section h2, section h3, section h4, section h5, section h6, aside h1, aside h2, aside h3, aside h4, aside h5, aside h6, { font-weight: bold; } 

А с псевдоклассом достаточно будет вот этого:

 CSS :is(article, section, aside) :is(h1, h2, h3, h4, h5, h6) { font-weight: bold; } 

Псевдоклассы :is() и :not()

В CSS есть псевдокласс :not() , который работает обратным образом. Он позволяет применить стили ко всему, кроме набора селекторов.

Ранее мы выбрали с помощью :is() все дочерние заголовки тегов article, section и aside. А с помощью :not() мы сможем выбрать все заголовки, которые не являются потомками этих элементов:

 CSS :not(article, section, aside) :is(h1, h2, h3, h4, h5, h6) { font-weight: normal; } 

Конструкция из псевдоклассов :is() и :not() выглядит логичной и интуитивно понятной.

Поддержка браузерами

В данный момент псевдокласс уже имеет поддержку большинства браузеров.

Для обеспечения кроссбраузерности вы можете использовать :any() и :matches() как фоллбеки для :is(). Например:

 CSS :-webkit-any(article, section, aside) h1 { font-weight: bold; } :-moz-any(article, section, aside) h1 { font-weight: bold; } :matches(article, section, aside) h1 { font-weight: bold; } :is(article, section, aside) h1 { font-weight: bold; } 

В заключении

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

Источник

A guide on HTML name vs id attribute

Posted on Aug 06, 2021

Although both name and id attributes are used to add identifiers to your HTML tags, the two attributes have different purposes for their existence.

This tutorial will help you learn about their differences.

The purpose of the name attribute

The name attribute is an identifier attribute that’s used for sending data through the HTML form elements.

For example, consider the HTML form as shown below:

The HTML form above intends to capture the user input for username and password, but since both elements don’t have the name attribute attached to them, the browser won’t send anything when the submit button is clicked.

Submitting the form using the GET method will generate the following URL:

 Now let’s add the name attribute to both elements as shown below:

 The same process also applies to an HTML form that uses the POST method.

Without the name attribute, any value you have in the HTML form element such as , , or element will be excluded from the form submission.

The purpose of the id attribute

The id attribute is a unique identifier for HTML tags meant to single out the element when rendered on the browser.

The element using the id attribute usually has a unique styling attached so that it stands out from the rest.

    element where the first item is colored red. This is one example of how you can create the element:

You can then create a CSS rule for the id using the hash ( # ) selector as follows:
Having two or more elements with the same id attribute value in one page is considered invalid, but you won’t receive any error because browsers are made to be fault-tolerant when it comes to rendering HTML.

In the past, the rule for CSS styling is that unique styles are applied to the id while general styles are applied to the class .

But since modern CSS practice tends to style everything using class – especially utility first CSS framework like Tailwind – the id attribute is now mostly used to associate the tag with an input element.

id attribute for labels

The id attribute in form elements can be used to associate a tag with a specific input element.

For example, consider the following HTML form code:


When you click on the label from the browser, you will automatically shift the browser focus to the element:

Without the for or the id attribute, the browser will do nothing when you click on the element. The same rule apply to other input elements like and .

Now you’ve learned the difference between the name and the id attribute. Nice work 😉

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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