w3resource

HTML CSS Exercise: Create a speech bubble shape with CSS3

Solution:

HTML Code:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset=utf-8><!-- Define the character encoding of the document as UTF-8 -->
<title>Create a speech bubble shape with CSS3</title><!-- Set the title of the HTML page -->
<style type="text/css">
/* CSS styles start here */

#speech-bubble {
width: 120px; /* Set the width of the speech bubble */
height: 80px; /* Set the height of the speech bubble */
background: #5ac4ed; /* Set the background color of the speech bubble */
position: absolute; /* Set the position of the speech bubble */
left:100px; /* Set the distance from the left edge of the containing element */
   -moz-border-radius: 10px; /* Set the border radius for Mozilla Firefox */
   -webkit-border-radius: 10px; /* Set the border radius for WebKit browsers */
border-radius: 10px; /* Set the border radius for other browsers */
}

#speech-bubble:before {
content:""; /* Insert empty content before the speech bubble */
position: absolute; /* Set the position of the pseudo-element */
width: 0; /* Set the width of the pseudo-element */
height: 0; /* Set the height of the pseudo-element */
border-top: 13px solid transparent; /* Create the top triangle of the speech bubble */
border-right: 26px solid #5ac4ed; /* Create the right side of the speech bubble */
border-bottom: 13px solid transparent; /* Create the bottom triangle of the speech bubble */
margin: 13px 0 0 -25px; /* Set the margins to position the pseudo-element */
}

/* CSS styles end here */
</style>
</head>
<body>
<div id="speech-bubble"></div><!-- Create a div element with the id "speech-bubble" -->
</body>
</html>

Explanation:

  • This HTML and CSS code combination creates a speech bubble shape using CSS3.
  • The speech bubble consists of a main container div and a pseudo-element (::before) to create the arrow or triangular shape.
  • The main container div has a specified width, height, background color, and border radius to create the body of the speech bubble.
  • The pseudo-element is positioned absolutely relative to its container and is used to create the arrow shape using borders.
  • By adjusting the border properties of the pseudo-element, you can control the size and shape of the arrow.
  • The positioning of the pseudo-element is calculated using margins to align it properly with the speech bubble body.

Live Demo :

See the Pen speech-bubble-answer by w3resource (@w3resource) on CodePen.


Supported browser

Firefox logo Chrome logo Opera logo Safari logo Internet Explorer logo
YesYesYesYesYes

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.