Create a Comment Box in HTML and CSS

Spread the love

This tutorial explains how to create a simple comment box input in HTML, CSS, and JavaScript. Basically, it is a frontend functionality (that can be handled in both jQuery and Vue JS) to quickly append a comment to the webpage. Further, it can be submitted to the server through JSON to publish a comment in realtime.

You can use this simple project for appending strings to the page in comment forms, to-do lists, or feedback forms. Similarly, you can use this technique in any web project to quickly append the text to the page. Before starting with coding I would suggest checking the demo page to check the comment form in action.

This comment form only appends the comment text to a specific div element without actually publishing it on the page. So, the entered text will be lost after refreshing the page. You have to submit (and store) the comment to the server for permanent.

Comment Box HTML Code

In HTML, create a section with an id "app" and place a textarea (for comment input) and p element for comment output.

<section id="app">
    <div class="container">
      <div class="row">
        <div class="col-6">
          <div class="comment">
        <p v-for="items in item" v-text="items"></p>
          </div><!--End Comment-->
          </div><!--End col -->
          </div><!-- End row -->
      <div class="row">
        <div class="col-6">
      <textarea type="text" class="input" placeholder="Write a comment" v-model="newItem" @keyup.enter="addItem()"></textarea>
          <button v-on:click="addItem()" class='primaryContained float-right' type="submit">Add Comment</button>
        </div><!-- End col -->
      </div><!--End Row -->
    </div><!--End Container -->
  </section><!-- end App -->

The CSS Styles

After creating the HTML structure, now it’s time to style it using CSS. So, target the very first element "container" class and define its max-width 640px. Similarly, define the background, margin, and padding property as follows:

.container {
	max-width: 640px;
	margin: 30px auto;
	background: #fff;
	border-radius: 8px;
	padding: 20px;
}

Now, target the "comment" class and display it as a block element. Likewise, specify min-height, border, and padding property for commentClicked class ad described below:

.comment {
	display: block;
	transition: all 1s;
}
.commentClicked {
	min-height: 0px;
	border: 1px solid #eee;
	border-radius: 5px;
	padding: 5px 10px
}

You can style the textarea/comment box according to your needs. Anyhow, the basic styles of the comment input are given below:

.container textarea {
	width: 100%;
	border: none;
	background: #E8E8E8;
	padding: 5px 10px;
	height: 50%;
	border-radius: 5px 5px 0px 0px;
	border-bottom: 2px solid #016BA8;
	transition: all 0.5s;
	margin-top: 15px;
}

The "primaryContained" class defined the style for the comment submit button. Specify its background color, padding, box-shadow, and border-radius property as follows. You can set the custom color and font-size in order to customize it.

button.primaryContained {
	background: #016ba8;
	color: #fff;
	padding: 10px 10px;
	border: none;
	margin-top: 0px;
	cursor: pointer;
	text-transform: uppercase;
	letter-spacing: 4px;
	box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.25);
	transition: 1s all;
	font-size: 10px;
	border-radius: 5px;
}

Target the button class with a hover pseudo-selector in order to define the hover styles. There you can set a different background color that will show on the hover event. You can also set the 3D button hover effect if you want to make a mindblowing hover effect for your comment form.

button.primaryContained:hover {
	background: #9201A8;
}

The JavaScript for Displaying Comment

You can handle the comment string in both jQuery and Vue JS to submit and append the comment. So, load the jQuery and Vue JavaScript libraries by adding the following CDN link to your HTML page.

<!-- Vue JS -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js'></script>
<!-- jQuery -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>

Finally, initialize the comment append function in the jQuery document ready function and done.

$(document).ready(function(){ 
 
    $(".primaryContained").on('click', function(){
    $(".comment").addClass("commentClicked");
  });//end click
  $("textarea").on('keyup.enter', function(){
    $(".comment").addClass("commentClicked");
  });//end keyup
  });//End Function

new Vue({
    el: "#app",
    data:{
       title: 'Add a comment',
      newItem: '',
      item: [],
    },
    methods:{
      addItem  (){
      this.item.push(this.newItem);
        this.newItem = "";
      }
  }

  });

That’s all! I hope you have successfully created a simple comment box using HTML, CSS, and JS. If you have any questions or suggestions, let me know by comment below.

Share it!

You May Also Like

41 thoughts on “Create a Comment Box in HTML and CSS”

  1. Thank you so much for this tutorial. This is exactly what I was needing for my project.

    One question, what would be the easiest way to get the comments to be persistent? When I refresh the screen, they are gone.

    Reply
    • Hi Nathaniel!
      In order to save comments on the server, you need to do a couple of things. First of all, create a table in your database named “comments”. You can run the following SQL query to create a table with the necessary columns.

      CREATE TABLE comments(
          id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
          username VARCHAR(50) NULL UNIQUE,
          email VARCHAR(255) NULL UNIQUE,
          comment TEXT NULL,
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP
      );
      

      After that create a “post-comment.php” file and paste the following script inside it to receive comments.

      <?php
      //Define variables for requested input fields
      $username = $email = $comment = "";
      
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
              
              $username = test_input($_POST["complainant-name"]);
              $email = test_input($_POST["bill-account"]);
              $comment = test_input($_POST["amount-payable"]);
      
              //connect to databse
              define('DB_SERVER', 'localhost');
              define('DB_USERNAME', 'root');
              define('DB_PASSWORD', '');
              define('DB_NAME', 'yourdbname');
      
              /* Attempt to connect to MySQL database */
              $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
      
              // Check connection
              if($link === false){
                  die("ERROR: Could not connect. " . mysqli_connect_error());
              }
          
              $sql = "INSERT INTO comments(
              username, 
              email, 
              comment
              )  
              
              VALUES (
              '".$username."', 
              '".$email."', 
              '".$comment."
              )";
              
              if ($link->query($sql) === TRUE) {
                  
                  echo "Your comment has been submitted!";
                          
              } 
              else {
                  echo "Error: " . $sql . "<br>" . $link->error;
              }
          
              $link->close();
      
      }
      else {
          //nothing
      }
      
      function test_input($data) {
          $data = trim($data);
          $data = stripslashes($data);
          $data = htmlspecialchars($data);
          return $data;
      }
      
      ?>
      

      Finally, add the action attribute with your comment form and done.

  2. Hi, thank you for tutorial.
    One question. How can I only show the commenting option without showing all the comments underneath the pictures or post we used the commenting feature

    Reply
    • Hi Vinuka, Sorry didn’t understand what you mean by showing the commenting option. Can you please explain in a bit more detail? Do you want always show the comments? If so then you need to handle it through the database and using PHP. Thanks.

    • Hi ScarAtlas, Do you mean you need a fully working comment section like our site? If so to build a similar comment section that is on our site, you can use WordPress CMS. If you only need design then you can need to code it using HTML/CSS. Thanks.

    • Chidi, There is no PHP file. This comment form develop using HTML/CSS only and if you want to make it work so users can comment on your site then you need to developed it using PHP or integrate it with any CMS such as wordpress.

    • You can define action attribute like

      <form action="post-comment.php"></form>
      

      And the post-comment.php is a file where you will write your PHP code.

  3. Hey. I want to add the comment section to a website of my own, which i coded from scratch. I can do html, css, and basic JavaScript but no php. Can you please explain in detail how to make comments stay on the page with php.

    Reply
  4. Do you know what the comment form is, you said it on a reply to a comment earlier on.If you do, can you please tell me?

    Reply
  5. Hi! well, first of all thanks! actually, I messaged because I had a little problem with the way you said for saving comments and that is it just doesn’t worked for me and I don’t know why; so I wanted to ask and see if there is any other way or not!

    Reply
    • Hi Zeinab!
      You’re welcome. Actually, it depends upon your project on how you handle comments in the database. This tutorial only explains the frontend design for a comment box.

    • Hi Jeremiah!
      You can make the comment box scrollable by defining fixed height along with the "scroll" value for the overflow property.

      .comment{
          height: 300px;
          overflow-y: scroll;
      }
      

      The overflow-y property with scroll value enable vertical scrollbar, if you also want horizontal scroll, you can use overflow-x or simply overflow property for both horizontal and vertical scroll.

  6. first, I want you thank you for your tutorial; it is exactly my problem I have to solve

    I want to integrate a comment-section on a Website and I would like to know if there are any tips you have for me

    Second, I have to know where to write this part:
    CREATE TABLE comments(
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NULL UNIQUE,
    email VARCHAR(255) NULL UNIQUE,
    comment TEXT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );

    Reply
    • You’re welcome! this is mySQL query to create a basic table for comments. You can manually create a table in the database or execute this query. If you are not familiar with database and SQL, please check a tutorial on Youtube.

  7. where shall i write the comment append function in the jQuery document ready function? I don’t understand where it has to be

    Reply
    • Hi Derek Wong!
      Simply, you can append the username next to the comment by writing the following HTML inside the “col-6” class.

      <div class="username"> <b> Username </b></div>
      

      You need to use this in backend, get the username through session variable and show the username with their comments.
      Actually, this form is frontend design only, you need to have a backend system to save comments and usernames.

  8. this is amazing! it would be nice if someone who managed to do it could create a simple guide to integrate the PHP functionality to make the comments persistent that you have explained in the comments.

    Reply
    • Yep, you are right, unfortunately, our domain isn’t PHP and we post tutorials only related to HTML/CSS. I will try to get some references added to the post.

Leave a Comment