One place for hosting & domains

      Common

      Common Cyber Attacks on Machine Learning Applications


      Machine learning (ML)
      algorithms and models ingest large amounts of data and use pattern recognition to make predictions and adjustments based on that data. ML powers chatbots, product recommendation systems, self-driving cars, and assists in decision-making in the health and financial sectors. Due to the prevalence of tools and frameworks like
      TensorFlow
      and
      PyTorch
      , developers are now able to add ML to their applications with less effort. Before getting started with machine learning, you should be aware of the most common machine learning cyber attacks. When thinking about the security of your ML application, you must consider the following areas:

      • Data: If your data is corrupted in any way, you will not obtain reliable our useful results from your machine learning models.
      • Application: When a model becomes corrupted, even the most perfect data produces incorrect results.
      • Output: An application only produces the output it’s designed to provide. Altering an application to perform tasks other than what it was designed to perform is a misuse of the application.
      • User: Even if all of the other security factors for a machine learning application are correct, users can easily thwart machine learning applications through various means, such as purposely providing bad input or misinterpreting the output.

      This guide discusses the top security vulnerabilities that you may encounter in a machine learning project. Some of these vulnerabilities are common to all software development projects, while others are unique to machine learning ones.

      Evasion

      The evasion attack is the most common issue facing machine learning applications. This attack seeks to modify input data in order to “trick” ML classifiers. For example, a successful evasion attack can insert a malicious algorithm into your application that slightly modifies an image, causing it to be misclassified by the machine learning algorithm. An evasion attack seeks to infiltrate a system in the following ways:

      • Attachment: An attachment can contain malicious code that executes the moment the file is opened.
      • Link: The malicious code executes as soon as the resource pointed to by the link is opened.
      • Image: Viewing an image within a user’s email setup can invoke the malicious code.
      • Spoofing: A hacker impersonates a trusted party.
      • Biometric: Using specially crafted code or other techniques, the attacker simulates a facial expression or fingerprint to gain access to a system.
      • Specially crafted code: It’s possible to train a machine learning model to perturb the output of a target model.

      Poisoning

      A poisoning attack is orchestrated by injecting false information into an application’s data stream, with the goal of producing inaccurate results. There are a number of situations where poisoning may occur. Here are the most common:

      • Using bad data during model training from unreliable or unvetted sources.
      • Providing large amounts of skewed or biased input after model training.

      The attacker usually prefers stealth in this case because the goal is not to bring the system down. Instead, the attacker seeks to change the output in a manner that favors the attacker in some way.
      SVM classifiers
      are often the focus of such attacks because the attacker uses them to perform tasks such as to redraw political or sales boundaries, or to give a particular product an edge during a sales campaign.

      Inference

      If a hacker determines which records from a dataset are used to train a machine learning model, that information can be used to look for vulnerabilities. An inference attack uses data mining and analysis techniques to gain knowledge about the underlying dataset. In most cases, the best results come from
      overfitted models
      . Overfitting happens when a machine learning model follows the original data points too carefully. This makes it possible for the hacker to query a particular data point with relative ease. This attack vector currently works only on
      supervised learning models
      and
      Generative Adversarial Networks (GANs)
      .

      As a hacker sends queries to the model, the model makes predictions based on the confidence levels for each class that the model supports, giving the hacker valuable insights into the underlying application. The worst part of this particular attack is that
      it’s often used against specific people and their data
      , such as their medical records.

      Trojans

      A trojan employs various techniques to create code or data that looks legitimate, but is really designed to take over the application or manipulate specific components of it. The concept of using a trojan against an application is old and is used against applications of all stripes. However, in the case of machine learning, the trojan often remains hidden and seeks to discover more about the data used by the machine learning application, rather than performing more overt tasks, such as deleting files. There are many kinds of trojan attacks, but the list below contains some of the most common for machine learning:

      • Backdoor: Creates a backdoor on the target computer that the hacker can use to remotely control the computer. Remote access allows the hacker to do just about anything desired, including downloading your dataset or model, corrupting a dataset, or causing the model to perform in an unexpected way.
      • Banker: Focuses on a strategy for obtaining or manipulating financial information. When considering the machine learning aspect of this Trojan, you must think about the sorts of information that this Trojan could obtain, such as membership inference, to obtain data, or evasion, to potentially obtain credentials. However, the goals are always to somehow convince a user to download a payload.
      • Downloader: Targets systems that are already compromised and uses its functionality to download additional malware. This malware could be anything, so look for any sort of unusual activity that comprises any part of your system, including your data.
      • Neural: Embeds malicious data into the dataset to create a condition where an action occurs based on an event, like a trigger. In most cases, the attack focuses on changing a neural network’s weights to apply to only certain nodes. This kind of Trojan is most effective against Convolutional Neural Networks (CNNs), although current research shows that you can also use it against Long-Short-Term-Memory (LSTM) and Recurrent Neural Networks (RNNs).

      Backdoors

      This kind of attack uses system, application, or data stream vulnerabilities to gain access to the underlying system or application without providing required security credentials. The focus is on the neural network itself, rather than on specially prepared inputs. Even though this attack is data based, the attack focuses on corrupting the neural network, as is the case with a trojan. The backdoor attack relies on an attacker modifying training data in some manner to gain access to the model, usually through the underlying neural network. Because this kind of attack is so subtle, a separate application is often required to locate and get rid of it.

      Espionage

      An espionage attack involves stealing classified and sensitive data, or intellectual property to gain an advantage over a person, group, or organization. Essentially, this kind of attack involves stealth to
      spy on an organization’s activities to obtain a particular result
      . The attack can go on for years because the attacker’s goal is to remain undetected for as long as possible. The results of the attack are normally subtle too, such as redirecting some, but not all, sales to a particular product. This form of attack can target machine learning data and models. It locates the data by using predictive models to look through logs for particular patterns of access.

      Sabotage

      Sabotage performs deliberate and malicious actions to disrupt normal processes, so that even if the data isn’t corrupted, biased, or damaged in some way, the underlying processes don’t interact with it correctly. Often, sabotage is highly detectable, but at the moment of detection, it’s already too late to do anything about it.
      Financial institutions are particularly susceptible to sabotage
      due to the incredible amounts of data used to create and manage models. In addition, sabotage is often hard to fix because the underlying data must be remediated first and then the model rebuilt.

      Fraud

      Fraud occurs when hackers rely on various techniques, such as phishing or communications from unknown sources, to undermine system, application, or data security in a secretive manner. This level of access can allow for unauthorized or unpaid use of the application and influence ways in which the results are used, such as providing false election projections. Fortunately, there is a lot of research pending that also uses
      machine learning techniques to detect and help mitigate fraud
      .

      Conclusion

      Before adding ML to your project, you should know about the types of cyber attacks that are frequently targeted at machine learning powered applications. Evasion, poisoning, and inference are some of the most common attacks targeted at ML applications. Trojans, backdoors, and espionage are used to attack all types of applications, but they are used in specialized ways against machine learning. Now that you are familiar with the cyber attacks to look out for, you can get started creating an ML powered application, by
      installing TensorFlow on Ubuntu 20.04
      .



      Source link

      Your Guide to Common Redirects (+ Use Cases)


      When updating your website’s content, you may find that you’ve accidentally created some broken links. That’s okay, it happens!

      You see, when a URL changes and it’s not properly redirected, it will cause those broken links, also known as 404 Errors. These issues harm user experience and Search Engine Optimization (SEO).

      The good news is that you can use redirects to fix broken links by rerouting traffic from old content to new web pages. In this way, you can optimize your website’s structure and avoid common front-end errors.

      This post will discuss what redirects are and when you might consider using them. Then we’ll give you an overview of the basic redirect types and explain how you can implement them on your website. Ready?

      An Introduction to Redirects

      A redirect is a method that takes users visiting an old URL and sends them to a new page. Whenever a visitor clicks on the original URL, the redirect takes them to the relevant, updated page the site owner wants them to find instead.

      One of the main reasons to use a redirect is to prevent visitors from seeing error pages. For example, if there are any broken links on your site, users may see a 404 error instead of the content they came for. This is also known as a 404 (Page Not Found) error:

      404 error page

      After encountering a 404 message, visitors are more likely to leave your website. This is not ideal under any circumstances. Plus, a higher bounce rate can harm your SEO.

      However, you can avoid these issues by using a redirect. You can send users to relevant content even after the URL changes. Here are some instances when you might need to redirect a link:

      Redirects can offer many benefits, but only when used correctly. Therefore, it’s important to consider some redirect best practices. That way, you can avoid common mistakes.

      For example, ‘redirect chains’ occur when there are multiple redirects going from the original content to the final URL. This can increase page loading time, decrease link equity, and negatively impact SEO.

      If your content has a redirect loop, this means there are multiple redirects that eventually lead back to the original URL. As a result, visitors may end up waiting longer for the same error message instead of your content.

      To check your website for redirect chains and loops, you can use a platform such as Screaming Frog. This tool provides a website crawler that can audit redirects:

      Screaming Frog SEO SPider

      With Screaming Frog’s SEO Spider, you can bulk check your redirects. Using this tool, you can identify any redirect loops or chains and use a new redirect to fix any problems.

      6 Types of URL Redirects (And Why You Might Use Them)

      Now that you know the basics of URL redirects, let’s discuss the available different types. That way, you can choose the best option for your website.

      301 Redirect

      A 301 redirect is a permanent redirect from a deleted or moved web page. This is one of the most common redirect types.

      Since a 301 redirect is permanent, you’ll want to use this option only when you don’t need to access the original content again. When you implement a 301 redirect, its code informs search engine crawlers that certain content has been removed and no longer needs to be indexed.

      You should consider using a 301 redirect when:

      • Permanently deleting a website page
      • Moving your website to a new domain
      • Changing a page URL by shortening or cloaking links
      • Consolidating multiple pieces of content into a combined web page

      A 301 redirect can be very useful for improving the user experience on your website. With it, you can permanently prevent users from seeing a 404 error page.

      For instance, if one of your products is no longer available, you could redirect traffic to your other product collections. This can keep visitors on your website by giving them similar recommendations:

      product recommendations page

      This tactic may also benefit your SEO. For instance, with 301 redirects, you can merge multiple pieces of thin content into a single in-depth resource. This is a smart way to repurpose content and improve underperforming web pages.

      302 Redirect

      A 302 redirect is similar to a 301, except that it’s a temporary redirect. It indicates that the original content has been temporarily moved to a new URL.

      On the browser side (i.e., from the user’s perspective), there isn’t much difference between a 302 and 301 redirect. However, a 302 redirect has a different HTTP response status code. This code informs search engines not to update their links to the original resource.

      Consider using a 302 redirect when:

      • Making changes to the original content
      • Performing A/B testing
      • Informing your audience about sold-out products

      302 redirects can often improve user experience by keeping visitors informed about website changes and updates. For example, you could temporarily redirect to a countdown page when relaunching a product:

      countdown page

      The best part about 302 redirects is that you can return to the original content at a later time. So rather than permanently preventing search engines and viewers from seeing certain pages, you can simply redirect to a temporary stand-in page.

      303 Redirect

      A 303 redirect is an HTTP response status code that means “see other.” Similar to a 302 redirect, it is a temporary code that informs the browser and search engine that the original content was replaced with a similar resource.

      The main difference between 303 and 302 redirects is that a 303 is not cacheable. This can be useful if you don’t want Google to store a certain web page over the long term.

      303 redirects are useful for rerouting after PUT or POST request methods. This ensures that refreshing the page doesn’t trigger the redirect again.

      For example, you can use a 303 redirect to handle form submissions. These are commonly used to redirect to thank you pages after entries:

      form submission success page

      After a visitor completes the form, a 303 redirect won’t allow them to use the back button to refresh the page. By using this redirect, you can avoid receiving duplicate form submissions.

      307 Redirect

      Another temporary option is the 307 redirect. This is a server-side redirect that informs search engines that you might change the URL in the future. What makes a 307 redirect unique is that it requires the HTTP request method to stay consistent.

      Although they are similar to 302 redirects, 307 redirects can be more clear. That’s because a 307 redirect doesn’t allow conversions from the POST to the GET request method.

      You may want to use a 307 redirect when running a recurring promotion or giveaway. This can be useful for performing frequent URL updates:

      example of online sweepstakes web page

      A 307 redirect can enable you to periodically update a link’s content while still using the original URL. This way, you can avoid losing any web traffic.

      308 Redirect

      Similar to a 301 redirect, a 308 redirect indicates that the original URL is being permanently relocated. However, 308 redirects don’t allow changing the request method from POST to GET.

      You can use 308 redirects for all the same 301 redirect use cases, such as when permanently moving a resource to a new location. Additionally, a 308 redirect can come in handy when you’re migrating a website that contains many forms created via the POST method.

      Additionally, using a 308 redirect can give you greater control over browser requests. Since you can specify either a POST or GET request method, this can often be cleaner and more efficient than 301 redirects.

      Meta Refresh

      Unlike the other methods on this list, a meta refresh is a client-side redirect. Instead of redirecting on the web server, this happens in the web browser. You might recognize this redirect as a refresh countdown timer on certain pages:

      meta refresh temporary web page

      You can use this type of redirect to refresh a web page that a visitor is already on. This can be beneficial for updating dynamic web pages such as online auctions.

      Unfortunately, implementing a meta refresh can also come with some downsides. When you use this technique, search engines could possibly flag your website as spam. Also, meta refreshes can impact user experience due to increased loading times.

      Skip the line and get tips right in your inbox

      Click below to sign up for more how-to’s and tutorials just like this one, delivered to your inbox.

      marketing tips

      How to Implement Redirects (3 Methods)

      Each redirect type can offer specific benefits to your website. As such, you’ll want to carefully consider which is the most appropriate redirect for your goals. Then, you can easily implement your redirects via one of the following methods.

      1. Use a WordPress Redirect Plugin

      WordPress is open-source software, and web developers are always creating new plugins to enhance its functionality. For WordPress website owners, a redirect plugin is one of the simplest ways to create your redirects.

      If this option appeals to you, we’d recommend downloading and installing the Redirection plugin. This is a free tool that enables you to manage all of your redirects in one place:

      WordPress Redirection plugin page

      If you use this plugin, you won’t have to rely on complicated coding. As long as your WordPress website supports permalinks, you can use Redirection to scan for broken links and fix them with redirects.

      To get started, navigate to your WordPress dashboard. Then go to Plugins > Add New. Look for the Redirection plugin using the search tool. When you find it, simply install and activate it:

      install Redirection page

      Next, go to Tools > Redirection. This will allow you to create new redirects or edit existing ones:

      add new redirect

      Click on Add New, and enter both the source URL and the target URL:

      add new 301 redirect Redirection

      Then, find HTTP code in the advanced options and pick from the list of redirect types. You’ll be able to choose from 301, 302, 303, 304, 307, and 308 redirects:

      Redirection plugin advanced options screen

      When you’re finished customizing your redirect, click on Add Redirect. It’s as simple as that!

      2. Create a Redirect Using Your .htaccess File

      .htaccess is a configuration file that you can use to make changes to your server software. Using this method, you can redirect certain URLs, make custom 404 error pages, and change your permalinks from HTTP to HTTPS. However, this file is only accessible on Apache servers.

      You can find your .htaccess file in your website’s root folder. Exactly how you access this will depend on your web host and plan. If you have a plan here at DreamHost, you can access your account, select the site you want to work with, and go to Manage Files. Look for the folder named after your site and click on it:

      .htaccess redirect

      Then locate the .htaccess file. Right-click on it, and choose Edit:

      .htaccess redirect

      Use the text editor to add your redirect code. If you’re redirecting from one internal page to another, here is the basic formatting you should use:

      Redirect [redirect type] [/path/to/old/file/old.html] [/path/to/new/file/new.html]

      If redirecting to an external page, replace the final part with the full URL for the page you want to send visitors to.

      For example, we implemented a 302 redirect. This is what our .htaccess code looked like:

      example .htaccess file

      If you’re implementing a meta refresh, you can use this code instead:

      <meta http-equiv="refresh" content="2;url=http://example.com/" />

      Once you’ve finished, click on Save & Close. Then you’ll probably want to check your work. To do this, simply visit the old URL in a browser to see if it directs to the new page.

      3. Make a Redirect in Your PHP file

      Another easy way to implement a redirect is by using PHP. This involves adding the header () function to a PHP file to direct visitors to a new URL. However, your original source will need to be a PHP file for this process to work.

      To get started, open a text editor. For those using a Microsoft computer, we’d recommend Notepad++. For Mac users, Tumult Whisk is a good alternative.

      Then, make sure the language is set to PHP. Open your source PHP file, and add your redirect code as the first line of the document. For example, a 301 redirect source code looks like this:

      <?php
      header("HTTP/1.1 301 Moved Permanently");
      header("Location: https://www.domain.com/the-new-name.php");
      header("Connection: close");
      ?>

      Remember that if you don’t define your 301 redirect in the header, it will automatically default to a 302 redirect. When you’re finished, save the file and test your results by visiting the old link.

      A Solution to Broken Links

      Broken links may increase your website’s bounce rate, but you can avoid this problem by using redirects. While 301 redirects are the most common solution for rerouting traffic, there are many other temporary options. By choosing the right redirect, you can avoid displaying 404 error pages and keep visitors on your website longer.

      With DreamHost, you can avoid this kind of complicated website management. We offer professional website management services that leave any technical problems to the experts. Check out our plans today to ensure that all your pages are primed for peak performance!

      Website Management Made Easy

      Let us handle the backend — we’ll manage and monitor your website so it’s safe, secure, and always up.

      DreamCare website tech support



      Source link

      How To Style Common Form Elements with CSS


      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Web forms are a common element of website design, ranging in complexity from a search form field to contact forms and complex data filtering. Knowing how to use CSS to style and work with these elements helps provide better solutions to these everyday problems, and can improve your user’s experience of your website.

      This tutorial covers the creation and styling of a web form that requests various data from the user. The form will use text fields, radio buttons, checkboxes, drop-down selections, a text area, and submit and reset buttons. You will create and style this form and its elements
      by resetting the styles with the appearance property, setting up your own consistent style for the form, adding placeholder answers for the text fields, and customizing the radio buttons and checkboxes with various pseudo-classes and pseudo-elements.

      Prerequisites

      Setting Up the Base HTML and CSS

      In this first section, you will set up the HTML and initial styles that you will work with throughout the rest of the tutorial. This HTML will set up the scaffolding of the page and create the form fields you will style later.

      Begin by opening the index.html file in your editor. Then, add the following HTML to provide a base structure for the file:

      index.html

      <!doctype html>
      <html>
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>CSS Form</title>
          <link rel="stylesheet" href="https://www.digitalocean.com/community/tutorials/styles.css" />
        </head>
        <body>
          <main>
          </main>
        </body>
      </html>
      

      The elements contained in the <head> element define the page’s name with the <title> element and where to load the stylesheet via the <link> element. The <meta> tags define the character encoding and instruct the browser on how to display the site on small-screen device. The main form contents will reside inside the <body> and <main> tags.

      Next, inside the <main> element, create a <form> element. Inside <form> you will add various form elements and <div> elements to help with layout. In this tutorial, additions to code from prior steps are highlighted. Add the highlighted HTML from the following code block to your index.html file:

      index.html

      ...
      <main>
        <form>
          <div>
            <label for="name">Name</label>
            <input id="name" type="text" />
          </div>
          <div>
            <label for="email">Email</label>
            <input id="email" type="email" />
          </div>
          <div>
            <label for="comp">Favorite CSS Compiler</label>
            <select id="comp">
              <option value="sass">Sass</option>
              <option value="less">Less</option>
              <option value="stylus">Stylus</option>
              <option value="postcss">PostCSS</option>
              <option value="other">Other</option>
            </select>
          </div>
          <div>
            <fieldset>
              <legend>Are you familiar with CSS Grid?</legend>
              <input type="radio" name="grid" id="yes" value="yes" />
              <label for="yes">Yes</label>
              <input type="radio" name="grid" id="no" value="no" />
              <label for="no">No</label>
            </fieldset>
          </div>
          <div class="full-width">
            <label for="message">Message</label>
            <textarea id="message"></textarea>
          </div>
          <div class="full-width">
            <input type="checkbox" id="newsletter" />
            <label for="newsletter">Receive our newsletter?</label>
          </div>
          <div class="full-width">
            <button type="submit">Send Response</button>
            <button type="reset">Clear Form</button>
          </div>
        </form>
      </main>
      ...
      

      HTML form structure consists of inter-connected attribute values in order to function correctly. This code creates a form that asks a user for their name and email, asks for their favorite CSS compiler and if they know CSS grid, provides a field for a user-generated message, and has a checkbox to sign the user up for a newsletter. To learn more about how to structure forms in HTML, see the Mozilla Web Docs page on web form structure.

      Be sure to save your changes to index.html, then create a new file in the same directory called styles.css.

      Open styles.css in your text editor. This file provides the styles that the browser will apply to the contents of index.html. Add the following CSS code to your styles.css file:

      styles.css

      body {
        margin: 0;
        background-color: hsl(0, 0%, 98%);
        color: #333;
        font: 100% / normal sans-serif;
      }
      
      main {
        margin: 0 auto;
        padding: 4rem 0;
        width: 90%;
        max-width: 60rem;
      }
      
      form {
        box-sizing: border-box;
        padding: 2rem;
        border-radius: 1rem;
        background-color: hsl(0, 0%, 100%);
        border: 4px solid hsl(0, 0%, 90%);
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 2rem;
      }
      
      .full-width {
        grid-column: span 2;
      }
      

      The body and the main element selectors create some initial text styling and layout for the overall page. The form element selector creates the styles for the overall form container and then defines a CSS Grid consisting of two columns of equal size with grid-template-columns: 1fr 1fr;. Then, the gap: 2rem provides 2rem spacing between each row and column in the grid. Lastly, the .full-width class selector allows containers with this class to extended between the two columns instead of staying in one column.

      Save your changes to styles.css. Next, open a web browser of your choice. Select the File menu item in the browser and then select the Open option. Next, navigate to your project folder and load your index.html file in the browser. The following image demonstrates how the page will render in the browser:

      Rounded white rectangle with a medium gray border on a light gray background. Several form field elements are in the white rectangle with black sans-serif labels.

      The form is displayed in a white box on a light gray background. Each form element is dispersed across the grid with the top four items alternating between the two columns and the last three stacked, spanning the two columns. The default styling of the form elements are as they appear in Firefox; each browser has a different default for styling form elements.

      In this section, you set up the initial HTML and CSS needed to work with form elements. You also learned that each browser handles the styling of these elements in a different way. In the next section, you will use the appearance property to equalize the styling of form elements across all browsers.

      Resetting Form Styling with the appearance Property

      Every browser handles the visual styling of form elements in a different manner. Often the styling of these elements goes beyond the initial capabilities of CSS and follows the aesthetic of the operating system or the browser’s own design language. In order to create consistent styling for all browsers, in this section you will use the appearance property and other properties to remove the default browser styles.

      To begin, open styles.css in your text editor. Create a new group selector consisting of button, fieldset, input, legend, select, and textarea. Then inside the selector block, add the appearance property set to none, as highlighted in the following code block:

      styles.css

      ...
      button,
      fieldset,
      input,
      legend,
      select,
      textarea {
        appearance: none;
      }
      

      The appearance property is the intended way to remove the special styling from form elements. However, due to the age and implementation of this property, most browsers still require a vendor prefix added to the property name. A vendor prefix is a special coded addition prepended to the property name as an identifier for a specific browser. For Chrome, Safari, and recent versions of Edge and Opera, that prefix is -webkit-. Firefox uses the -moz- prefix.

      When working with vendor prefixes, it is important to put the vendor prefix versions of a property first and end with the non-prefixed version. This way, older browsers that only support the prefixed property will use the prefix, but new browsers that support both prefix and the non-prefix versions will use the non-prefixed standard version. Add the highlighted prefix appearance properties as formatted in the following code block:

      styles.css

      legend,
      fieldset,
      select,
      textarea,
      input,
      button {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
      }
      

      Save your changes to styles.css and then open index.html in your browser. The appearance properties have removed the embellished styling and have gone to a simpler style, as rendered in the following image:

      Form elements with dark gray borders and middle gray borders creating depth effects.

      The appearance property only allows you to change the browser-specific styling. The biggest change the appearance: none property value made was to remove the radio buttons and checkbox completely. For the rest of the form elements, a few more properties are needed to completely remove the default styles. The highlighted CSS properties in the following code block add the necessary styles to remove the default styles:

      styles.css

      ...
      button,
      fieldset,
      input,
      legend,
      select,
      textarea {
        -webkit-appearance: none;
        -moz-appearance: none;
        appearance: none;
        background-color: transparent;
        border: none;
        padding: 0;
        margin: 0;
        box-sizing: border-box;
      }
      

      This CSS removes the background color and resets the parameters of the box model. Not all of these styles are necessary for all the elements, but it is acceptable to group these reset styles across all the elements.

      Save your changes to styles.css, then refresh index.html in the browser. The form elements have visually disappeared from the page, as shown in the following image:

      Black, sans-serif text in a white rectangle on a gray background.

      In this section, you used appearance and additional properties to completely remove the default styles from the form elements. You also used vendor prefixes to appropriately order apply the property for future browser versions. In the next section, you will begin customizing the visual styling of the form fields.

      Setting Consistent Styles Across Form Fields

      Now that the default browser styles have been completely removed, you will apply a consistent custom aesthetic across all the form elements. This will involve creating various group selectors that target specific form characteristics to receive the appropriate styles.

      To begin, open styles.css in your text editor. Then, create a group selector consisting of input, select, and textarea. Add the highlighted styles from the following code block:

      styles.css

      ...
      legend,
      fieldset,
      select,
      textarea,
      input,
      button {
        ...
      }
      
      input,
      select,
      textarea {
        border: 2px solid #333;
        background-color: white;
        border-radius: 0.25rem;
      }
      

      These styles add a 2px dark gray border around each of the data entry elements, along with a white background and rounded corners.

      Next, you will apply styles for the data entry elements that contain text inside. You will use an attribute selector to specify which input elements to target based on their type attribute value. The highlighted CSS in the following code block provide the styles for the necessary elements:

      styles.css

      ...
      input,
      textarea,
      select {
        ...
      }
      
      input[type="text"],
      input[type="email"],
      select,
      textarea {
        font: 1.25rem / 1.5 sans-serif;
        display: block;
        box-sizing: border-box;
        width: 100%;
        padding: 0.5rem 0.75rem;
      }
      

      These styles apply a consistent font size and family across all elements. The <textarea> element, for example, does not inherit the font settings from the body element. The display, box-sizing, width, and padding properties provide a consistent layout and structure for each of these data entry elements.

      Save your changes to styles.css and then open index.html in your web browser. As rendered in the following image, the fields now have a thicker dark gray border around them and the text of the <select> element is now much larger:

      Black, sans-serif text in a white rectangle on a gray background wth dark gray outline rectangles.

      Next, there are two elements that need some special styling in addition to the broad styling you’ve already written. The first is to give more height to the textarea, and the second is to apply a custom drop-down arrow to the <select> element.

      Return to styles.css and add a textarea element selector. Inside the selector block, create a min-height property set to a value of 10rem. This will create a larger initial area for the form user to fill in text. The highlighted CSS in the following code block illustrates how this is written:

      styles.css

      ...
      input[type="text"],
      input[type="email"],
      select,
      textarea {
        ...
      }
      
      textarea {
        min-height: 10rem;
      }
      

      After adding the styles for the textarea, the next thing to accomplish is to make an image directory. That can be done by running the following in your command prompt from within the same directory as your index.html and styles.css files:

      Next, run the following curl command to download the first image you will work with into the new images directory:

      • curl -sL https://assets.digitalocean.com/articles/68129/down-arrow.svg -o images/down-arrow.svg

      The image you downloaded is an SVG, which is a markup language similar to HTML with the purpose of drawing shapes.

      To add this new image to the <select> element, return to styles.css. Then, create a select element selector and add a background property with the highlighted value from the following code block:

      styles.css

      ...
      textarea {
        min-height: 10rem;
      }
      
      select {
        background: url("images/down-arrow.svg") no-repeat center right 0.75rem;
      }
      

      This background property loads the image into the <select> element’s background and does not repeat the image. Then it centers the image vertically with center and offsets it from the right side with right 0.75rem.

      Save your changes to styles.css, then return to your browser to refresh the page. The <textarea> is now about twice its original height and the <select> element has a blue downward-facing arrow on the right side. The following image illustrates how this is rendered in the browser:

      Black, sans-serif text in a white rectangle on a gray background with dark gray outline rectangles, one of which has a blue downward arrow.

      Throughout this section you created a custom aesthetic for the form’s data entry elements. You also created a background for the <select> element to replace the default arrow. In the next section, you will create custom radio buttons and checkboxes and apply selected states when they are checked.

      Customizing Radio Buttons and Checkboxes with the :checked Pseudo Class

      Now that you have created the base aesthetic of the form, it’s time to apply that visual style to the interactive input items of a radio button and checkbox.

      Start by opening styles.css in your text editor. You will change the input elements with a type attribute of radio or checkbox to have an equal height and width value. Then you will turn the radio buttons into circles. The highlighted portions of the following code block show how this is formatted:

      styles.css

      ...
      select {
        ...
      }
      
      input[type="radio"],
      input[type="checkbox"] {
        height: 1.5em;
        width: 1.5em;
        vertical-align: middle;
      }
      
      input[type="radio"] {
        border-radius: 50%;
      }
      

      The vertical-align property is meant for aligning inline text items. By setting this to middle, the input fields will sit in the middle of the text align. Then, the radio input with a border-radius property of 50% will create a circle because the height and width are the same.

      Save your changes to styles.css and then open index.html in your browser. The two radio buttons and the checkbox are now larger and more noticeable as rendered in the following image:

      Two circles with black sans-serif text and a rounded square with black sans-serif text.

      If you were to interact with the radio buttons or checkbox, nothing visible would happen. The appearance property also removes the selected indicators for these types of input. Next, you will use the :checked psuedo-class selector to apply styles to the selected input item.

      Return to styles.css and create a new selector for the radio button input with a :checked pseudo class. Then, inside the selector block, add a background-image with a radial-gradient so a filled-in style can be applied to selected radio buttons. The highlighted CSS from the following code block shows how this is formatted:

      styles.css

      ...
      input[type="radio"] {
        border-radius: 50%;
      }
      
      input[type="radio"]:checked {
        background-image: radial-gradient(
          hsl(213, 73%, 50%) 40%,
          transparent calc(40% + 1px)
        );
      }
      

      The calc() function allows the transparent property to be set 1px after the color value, creating a solid blue circle inside the input field.

      Save your changes to styles.css and return to index.html in your browser. The radio buttons now have a solid blue circle surrounded by white inside the input. The following image shows the Yes radio button selected:

      Two circles with black sans-serif text and a rounded square with black sans-serif text. One circle has a blue circle inside.

      Next, the checkbox will use a background image to indicate its :checked state, similar to the <select> dropdown’s arrow.

      Run the following curl command to download the checkmark image to your images directory:

      • curl -sL https://assets.digitalocean.com/articles/68129/check.svg -o images/check.svg

      Now that you have the image downloaded and ready to use, return to styles.css in your text editor.

      Next, add a input[type="checkbox"] selector with a :checked pseudo-class attached. In the selector block, add a background property that loads the check.svg image and scales it down to fit in the box. The highlighted CSS in the following code block indicates how this is written:

      stlyes.css

      ...
      input[type="radio"]:checked {
        ...
      }
      
      input[type="checkbox"]:checked {
        background: url('images/check.svg') no-repeat center / 75% auto;
      }
      

      The background property values ensure that the checkmark image is centered to the container, does not repeat, and is scaled down 75% proportionally.

      Save your changes to styles.css then refresh the page in the browser. When selecting the Receive our newsletter check box, now a checkmark appears inside, as illustrated in the following image:

      Square with rounded edge and a blue checkmark inside with black sans-serif text to the right.

      In this section, you created custom radio buttons and input fields and made them adjust their selected state through the use of the :checked pseudo-class. In the next section, you will style the <label> and <legend> elements on the page.

      Adding Special Styles to Labels and Legends

      The next elements to style are the <label> and <legend> elements in the form. There are two different styles that will be used: a small label style for the radio button and checkboxes and a large label style for the remaining elements.

      Open index.html in your text editor. You will add a class attribute to each <label> and <legend> with a value of either large-label or small-label, as highlighted in the following code block:

      index.html

      ...
      <form>
        <div>
          <label for="name" class="large-label">Name</label>
          <input id="name" type="text" />
        </div>
        <div>
          <label for="email" class="large-label">Email</label>
          <input id="email" type="email" />
        </div>
        <div>
          <label for="comp" class="large-label">Favorite CSS Compiler</label>
          ...
        </div>
        <div>
          <fieldset>
            <legend class="large-label">Are you familiar with CSS Grid?</legend>
            <input type="radio" name="grid" id="yes" value="yes" />
            <label for="yes" class="small-label">Yes</label>
            <input type="radio" name="grid" id="no" value="no" />
            <label for="no" class="small-label">No</label>
          </fieldset>
        </div>
        <div class="full-width">
          <label for="message" class="large-label">Message</label>
          <textarea id="message"></textarea>
        </div>
        <div class="full-width">
          <input type="checkbox" id="newsletter" />
          <label for="newsletter" class="small-label">Receive our newsletter?</label>
        </div>
        ...
      </form>
      ...
      

      Save these additions to index.html, then open styles.css in your text editor.

      In styles.css, add a .large-label class selector and add the following properties as highlighted in the following code block:

      styles.css

      ...
      .full-width {
        grid-column: span 2;
      }
      
      .large-label {
        display: inline-block;
        font: bold 1.5rem sans-serif;
        margin-bottom: 0.5rem;
      }
      ...
      

      These styles set the large-label elements to be large and bold with a font size of 1.5rem, which is equivalent to 24px. Then the margin-bottom property provides some space between the label and its counterparts.

      Save this change to styles.css and open index.html in your web browser. The label text above the data entry field will be large and bold, as rendered in the following image:

      Large, bold sans-serif text above black outline input fields.

      Return to styles.css and create another class selector for .small-label. Since these are the labels that are to the right of a radio button or checkbox, they will need some different spacing and sizing styles compared to the .large-label. Add the highlighted CSS to your styles.css from the following code block:

      styles.css

      ...
      .large-label {
        display: inline-block;
        font: bold 1.5rem sans-serif;
        margin-bottom: 0.5rem;
      }
      
      .small-label {
        vertical-align: middle;
        display: inline-block;
        margin-left: 0.25rem;
        margin-right: 1.5rem;
        font: 1.25rem sans-serif;
      }
      ...
      

      The vertical-align: middle will offset the text slightly. The font is set to 1.25rem, the equivalent of 20px, with sans-serif font. The margin properties on the left and right provide space between the input fields and the label.

      Save your updates to styles.css and refresh index.html in the browser. The labels next to the radio buttons and checkbox are now larger and provide more spacing, as rendered in the following image:

      Large, bold sans-serif text above black outline input fields with medium, thinner text.

      In this section, you created styles for two different types of labels based on where they were in relation to their input value. The labels now stand out, providing easier legibility and navigation throughout the form. In the next section, you will provide example data formatting through using the placeholder attribute.

      Providing Placeholder Content with the ::placeholder Pseudo-Element

      Placeholder content on an input or textarea element provides form users with a visual demonstration of what kind of information is being requested and how to format it. The placeholder attribute is added to the HTML with a value describing it. Then the ::placeholder pseudo-element allows for customizing the look of the text.

      To begin making placeholder content, open index.html in your text editor. Add a placeholder attribute to the name text <input />, the email <input />, and the <textarea> elements. The highlighted HTML in the following code block indicates where to add the placeholder and the value to use:

      index.html

      ...
      <form>
        <div>
          <label for="name" class="large-label">Name</label>
          <input id="name" type="text" placeholder="First or Full Name" />
        </div>
        <div>
          <label for="email" class="large-label">Email</label>
          <input id="email" type="email" placeholder="[email protected]" />
        </div>
        ...
        <div class="full-width">
          <label for="message" class="large-label">Message</label>
          <textarea id="message" placeholder="Leave a message…"></textarea>
        </div>
        ...
      </form>
      ...
      

      Save your changes to index.html, then open the page in a web browser. These three text entry areas now have content inside them. Once these text entry fields are selected and content is added, the placeholder text will be removed by the browser. The following image illustrates how the default placeholder styles appear in the browser:

      Black outline containers with light gray sample text inside.

      In order to style the placeholder, open styles.css in your text editor. Add a group selector for input::placeholder and textarea::placeholder. Be sure to use double colons between the selector and the pseudo-element, as this is how the browser recognizes the difference between a pseudo-class and a pseudo-element. The highlighted CSS in the following code block shows how this is written:

      styles.css

      ...
      textarea {
        min-height: 10rem;
      }
      
      input::placeholder,
      textarea::placeholder {
        opacity: 1; /* Firefox */
        color: hsl(213, 73%, 50%);
      }
      
      select {
        background: url("images/down-arrow.svg") no-repeat center right 0.75rem;
      }
      ...
      

      The one thing to note is that Firefox requires an opacity value set to 1 in order to have the full color value. Otherwise Firefox reduces the opacity, dimming the text color and causing accessible color contrast issues depending on the color value. Because this is a Firefox-only situation, a comment is there to explain the purpose of the opacity property’s presence.

      Save your changes to styles.css and return to the browser to refresh index.html. The placeholder text is now the same blue color used for the drop-down arrow and selected states for the radio button and checkbox. The following image illustrates how the browser renders the placeholder content:

      Black outline containers with blue sample text inside.

      With this section, you created placeholder content on text entry fields and styled them with the use of the ::placeholder pseudo-element. In the next section, you will create custom styles for form <button> elements.

      Creating Interactive Button Styles

      In web forms, <button> elements are often used to submit or reset a form. In index.html, there are two buttons, one with a type of submit and the other of reset. Both are functionally useful, but perform opposing actions. The submit button will send the form along to a processor, while the reset button clears all entered data from the form. Due to these different actions, the <button> elements need to look visibly different as well.

      To begin, open styles.css in your text editor and create a button element selector. In this selector block, you will add the styles that are shared between the submit and reset <button> elements, as highlighted in the following code block:

      styles.css

      ...
      input[type="checkbox"]:checked {
        background: url("images/check.svg") no-repeat center / 75% auto;
      }
      
      button {
        font: 1.25rem sans-serif;
        border-radius: 0.25rem;
        cursor: pointer;
        padding: 0.75rem 1.25rem;
      }
      

      The font sets both buttons to have the same font style and size. Then the border-radius adds a rounded corner to both buttons. The cursor property changes the style of the cursor to be the hand-style pointer. Lastly, the padding property defines the space around the inside of the button.

      Save your changes to styles.css and then open index.html in your web browser. The text in the button will grow and the spacing between the text will increase visually due to the padding. The following image shows how the buttons are rendered in the browser:

      Two phrases in dark gray on a white background.

      Next, return to styles.css to add styles for each button type by using an attribute selector targeting each. For the submit button, add a blue background-color and white text color. The reset button will gain a link-like underline and a margin to add more space between the buttons. Add the highlighted CSS from the following code block to your styles.css file:

      styles.css

      ...
      button {
        ...
      }
      
      button[type="submit"] {
        background-color: hsl(213, 73%, 50%);
        color: white;
      }
      
      button[type="reset"] {
        text-decoration: underline;
        margin-left: 1rem;
      }
      

      Save these additions to styles.css then refresh index.html in your text editor. The submit button is now a prominent blue and white, while the reset is subdued underlined text, as rendered in the following image:

      One phrase in white text in a blue container and another phrase in dark gray underlined text on white.

      The <button> element does not have a :hover state by default, so you will now add this to your style. A :hover state is useful to help cursor users have visual feedback that the cursor is situated on the buttons.

      To create :hover states for these <button> elements, return to styles.css in your text editor. Set the submit button’s backgound-color to darken on hover. Then, make the reset button drop the underline when hovered. The highlighted HTML in the following code block indicates how to write these styles:

      styles.css

      ...
      button[type="submit"] {
        background-color: hsl(213, 73%, 50%);
        color: white;
      }
      
      button[type="submit"]:hover {
        background-color: hsl(213, 73%, 40%);
      }
      
      button[type="reset"] {
        text-decoration: underline;
        margin-left: 1rem;
      }
      
      button[type="reset"]:hover {
        text-decoration: none;
      }
      

      Save your changes to styles.css and then return to the browser to refresh index.html. As the following animation portrays, the <button> elements shift their styles when the mouse cursor hovers over them:

      Animation of a blue button becoming darker on hover and underlined text losing the underline on hover.

      In this section, you created styles for the <button> elements so to make their differences visually noticeable. You changed how the cursor appears on hover by adjusting the cursor property. You also created custom styles to apply to each button to provide further visual feedback. In the last section, you will provide further visual activity feedback by creating styles when a form element is presently in use with the :focus pseudo-class.

      Clarifying the Active Form Fields With :focus

      When filling out a form, it is important for the user to know what field they are currently working on. You can accomplish this with the use of the :focus pseudo-class. By default, browsers employ an outline property to indicate when an element has :focus, but at times it may not be a noticeable indicator, or it may clash with other visual aspects of the design. In this section, you will create a custom :focus state that matches your form’s aesthetic.

      To begin working with form field :focus states, open styles.css in your text editor. Create a group selector for input, select, and textarea, all with a :focus pseudo-class, as highlighted in the following code block:

      styles.css

      ...
      input,
      select,
      textarea {
        ...
      }
      
      input:focus,
      select:focus,
      textarea:focus {
        outline: none;
        box-shadow: 0 0 0 4px hsl(213, 90%, 70%);
      }
      
      input[type="text"],
      input[type="email"],
      select,
      textarea {
        ...
      }
      ...
      

      These styles remove the browser default outline value and replace the style with a thick blue stroke created with the box-shadow property. The first three values of the box-shadow are for the shadow’s placement and blur amount. The fourth is called the spread, which in this case creates a 4px stroke around the focused element.

      Next, the buttons will receive a slightly different focus state, since the submit button is the same blue color. The purpose and intent of a focus state is to bring noticeable attention to the focused element, so you will distinguish these outlines in a different ways.

      Add a button:focus selector to styles.css. In the selector block, disable the outline default and add a box-shadow property. The placement, blur, and spread values will remain the same as the entry fields, but the color will be black instead of blue, as highlighted in the following code block:

      styles.css

      ...
      button {
        ...
      }
      
      button:focus {
        outline: none;
        box-shadow: 0 0 0 4px black;
      }
      
      button[type="submit"] {
        ...
      }
      ...
      

      Save your changes to styles.css and return to your browser. Refresh index.html and begin hitting the Tab key for the focus to shift between each element in the form. The following animation shows how the focus style is applied as the focus changes with the Tab key:

      Animation of form fields gaining a light blue outline sequentially.

      In this section, you created focus state styles that provide clear visual feedback when a form element has focus. This visual styling is helpful for mouse, touch, and keyboard input users.

      Conclusion

      Forms are a common element of web design. They allow users to interact with apps, search content, and provide feedback. In this tutorial, you created and styled a full-fledged form. You removed the browser default styles with the appearance property, and created a new custom aesthetic across various elements. You used the :checked pseudo-class to make selected states for radio buttons and checkboxes. Then you added placeholder content and matched the styling with the ::placeholder pseudo-element. After you created custom button styles, you applied :focus styles giving valuable visual interaction feedback to the form users.

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link