Comment Box in HTML & CSS Code

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 real-time.

You can use this simple project for appending strings to the page in comment forms, to-do lists, or feedback forms in HTML. 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 of 640px. Similarly, define the background, margin, and padding properties 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 properties for commentClicked the 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 Comments

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 = "";
      }
  }

  });

Note: The example provided above about creating an HMTL comment box is required an action page to process the content of the comment box when the user clicks on submit button.

What’s an “Action Page”?

An “action page” in web development is a web page that processes the data submitted by the user through a form. In the context of the content you provided earlier, an action page would be the page that receives and processes the contents of the comment box after the user clicks the “Submit” button.

Typically, an action page would contain a server-side script, such as PHP or Python, that processes the form data and performs some action with it, such as saving it to a database or sending it in an email.

Add Comments the Easy Way

There are free scripts available online that can help you create an action page to process the contents of a comment box submitted by users on your website. However, creating an action page can be complex, so using a pre-made script can be a simpler solution.

One such solution is HTMLCommentBox.com, which provides an easy way to add a comments section to your website by copying and pasting code. However, to moderate comments, you’ll need to log in using a Google account.

The advantage of using a pre-made script like this is that it’s free and easy to use. But keep in mind that you may have less control over how the script handles user comments. You can customize the comments section to some extent, but the level of control may be limited.

Ultimately, the decision to create your own script or use a pre-made one is up to you. There are also other pre-made guestbook scripts available online that you could consider, such as those from Matt’s Script Archive or JsWidget.com.

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 commenting below.

You Might Be Interested In:

Muhammad Asif is a Front End Developer and Editor Staff at Codeconvey.com. He enjoys experimenting with new CSS features and helping others learn about them.

61 thoughts on “Comment Box in HTML & CSS Code”

  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.

    • 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

    • 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.

  3. How do I make a comment section like the one you have here?

    • 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.

  4. On the comment earlier on, you said PHP file.Where would you make this file.

    • 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.

  5. On a comment earlier you said ‘add the action attribute’.Can you please tell me how you would do that

    • 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.

  6. 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.

  7. 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?

  8. 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!

    • 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.

  9. Hi, I was wondering how would I make the comments scrollable so that they don’t take up the whole page?

    • 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.

  10. Is there any way to save the commments without SQL database?

    • Hi Morah!
      There is no way to save comments without using Database.

  11. Hi. May I know how can use session storage in this comment box?

    • You need to take help of Javascript or PHP to storage sessio.

  12. Hey this tutorial is awesome

    could I ask you if i get problems? I have a very similar project like that

    • Hi Thomas Kujawa!
      How can I help you?

  13. 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
    );

    • 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.

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

  15. and the HTML page is ready like in your example? I don’t see any oder Section

    • yep, you can use the HTML page just like our demo.

  16. Hello, this has helped me alot but I was wondering on how to make it so the post displays the Users name with their comment?

  17. How can we have the users name show next to their comment?

    • 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.

  18. 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.

    • 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.

  19. Hey, nice tutorial
    how do you make the time when the comment was posted show and also the name of the user who posted it

    • Hi Tofunmi, To show the comments posted you need to integrate them with PHP or WordPress. This is an HTML/CSS example of a tutorial. thanks.

  20. Thank you so much for this. You have no idea how much it helped me with a project I am doing for a friends wedding website. I just started coding and this helped so much!

    • Hi Stef!
      Glad to know that this tutorial was helpful for you. You can visit our site in the future for more free coding tutorials with example source codes.

  21. Hey. how do you make a like button appear after each comment is posted

  22. Hi! Why didn’t the coding work after I copy and pasted it in notepad and turned it to HTML?

    It stopped working after the .container part

    • Lina, You can download the readymade template and then copy the code from the index.html and style.css file.

  23. I tried making comments happen on my game but it didn’t work, and it’s really stressing me out because I’ve been trying to add comments for an hour
    My game is spilt into files, so how do i connect the Javascript file and the html file containing the code for having comments?

    • Dragoness, This is plain html/css design file and you should coding to make it work.

  24. how do I get the input to display like yours. I copy your code and pasted but the comment or input is not displaying

  25. This example is a good one… BUT, do you have one that shows:

    This example of (I call style 1) comment after comment
    https://codeconvey.com/Tutorials/comment-box-in-html-and-css/

    could be mixed with (I call style 2)
    https://codeconvey.com/Tutorials/css-comment-box/#

    to provide the style of the 1st, with the info comment box the style of the 2nd (but no website address necessary) and send the email address to somewhere (mail chimp?) to be collected.

    Want it simple not complex. Only show Who Said, and What was said
    to be displayed

    I have a screen sample mockup that I could send you, but your post does not allow uploads. So email me for the copy

  26. And need to limit the number of characters of a comment to about 100

    • Hi Dmmafs!
      You can use the maxlength attribute for the textarea element to set the maximum limit for characters. So, edit the comment box HTML, find the textarea and add the maxlength attribute:

        <textarea maxlength="100" type="text" class="input" placeholder="Write a comment" v-model="newItem" @keyup.enter="addItem()"></textarea>
      
  27. I am 79 and realize this will be my last website. My brain “has left the building.” The website is designed around your “comment-box” with comments accumulated until I reset them. I have tried and just can’t do it. I know it is my failing but need someone to do this for me. The website is thepeoplesright.com. PLEASE help me.

    • Thanks for your feedback! Keep visiting us for more free web design tutorials.

  28. Yo so it doesnt work. I click the button to add comment and it doesent want to

Comments are closed.