How to Add Images in Markdown

How to Add Images in Markdown
Hostman Team
Technical writer
HTML
17.01.2025
Reading time: 4 min

When visiting any website, you’ve likely noticed that images make the pages more engaging and visually appealing. If content were limited to text alone, it would look dull and monotonous. Visual elements help users better understand and remember information while also making the interface more user-friendly.

Markdown is a simple and user-friendly markup language used to create text with minimal effort. It’s widely used for writing documentation, articles, and blog posts. Markdown also allows you to add images to your text, which play a crucial role in visualizing content, making it more comprehensible and memorable.

Key Methods for Adding Images

There are two primary methods for adding images in Markdown: using local images and external links.

Local Images

It’s essential to correctly specify the file path to insert images stored locally. It’s recommended to store images either in the same directory as the Markdown file or at the same hierarchical level.

  • If the image is in the same directory as the .md file, simply provide the file name:

![Computer](computer.png)
  • If the image is in a subdirectory (e.g., /img) within the project folder, specify the path as follows:

![Computer](img/computer.png)

The text in square brackets ([Computer]) is the alternative text (alt-text). This text appears if the image fails to load and helps screen readers describe the image for visually impaired users.

The image path is enclosed in parentheses. Ensure the path is correct to avoid issues with image display after uploading to a server.

External Images

To insert an image hosted on the internet, use its URL:

![Image Description](https://site/photo.png)

Advantages of using external images:

  • Saves repository space: You don’t need to store large image files locally.

  • Easy content management: It’s convenient when images are updated frequently.

Disadvantages:

  • Dependency on the external source: If the image is removed or the URL changes, the image will no longer display.

Image Size

In standard Markdown, there is no built-in support for controlling image sizes (except for platforms like GitHub and others where this feature has been manually added), but you can use HTML for this purpose:

<img src="/img/computer.png" alt="Computer" width="500" height="300">

Enhanced Formatting

Enhanced formatting helps draw attention and makes the content more accessible and easier to read.

Image Caption

Captions for images are important as they provide additional information to the reader.

![Computer](/img/computer.png "Text below the image")

Clickable Image

To create a clickable image that links to another resource, wrap the image syntax in square brackets with a link:

[![Computer](/img/computer.png)](https://site)

Effective Alt Text

Alt text should describe the content of the image and be clear for all users.

Bad alt text:

![Computer](/images/picture.jpg)

Good alt text:

![The first computer ever built](/img/computer.png)

Why is Alt Text Important?

  • Accessibility: Users with visual impairments use screen reader programs that read the alt text aloud.

  • SEO: Search engines index alt text, helping your content to be found through search queries.

Tips for Working with Images

  • Try to use images with the smallest file size possible to speed up page loading.

  • Optimize images before uploading to avoid large file sizes and long loading times.

  • Ensure that the alt text is unique and accurate.

  • The file name should be relevant and include keywords. For example, instead of img123.png, use computer-setup.png.

Comparison of Methods for Inserting Images

There are various methods to insert images, each with its own pros and cons. Below is a comparison table.

Method

Advantages

Disadvantages

Markdown syntax

Simple and fast insertion

Less flexibility in customization

HTML markup

Full control over style and size

More complex syntax

Combination of Markdown and HTML

Combines simplicity and flexibility

Requires basic HTML knowledge

Conclusion

Now you know how to insert images in Markdown, control their size, add captions, and make content more accessible using alt text. Using images makes the text more visual and helps readers better comprehend the information.

Check out our reliable and high-performance WordPress hosting solutions for your WordPress websites.

HTML
17.01.2025
Reading time: 4 min

Similar

CSS

How to Create a Draggable Element

The term Drag-and-Drop refers to the action of moving items using the mouse. Most often, this action is associated with moving files into folders. The ability to drag and drop blocks and elements from one section to another makes website builders like Tilda and Wix so convenient. These platforms allow users to create pages without any programming knowledge. The easy-to-use interface makes it possible to build a landing page in just a couple of hours. Today, we will show you how to create similar draggable elements. How to Implement Drag and Drop Effect Using JavaScript The first thing to note is that we will implement the drag-and-drop functionality without loading any frameworks or JavaScript libraries. For the desired result, knowledge of the browser API and support for the following versions is enough: Firefox 3.5+, Chrome 4, 9+, Safari 6+, Opera 12+. Before writing the code, we must address two tasks: Determine what and where we are dragging (draggable element and dropzone). Decide what will happen to the dragged element once it is dropped. As usual, events are triggered in the browser when the specified conditions are met. Now, let's take a closer look at the events that occur until the object reaches the target area. Events When dragging elements, seven events are triggered. Even though their functions are intuitive, it's important to understand the circumstances under which they are triggered. Dragstart: This event is triggered when the dragging of the element begins as soon as the mouse presses down on the element. Dragenter: This event is triggered when the dragged element enters the target area (object). Dragover: The Dragover event occurs when the dragged element is within the target object's area but has not yet been released. Dragleave: This event occurs when the dragged element leaves the target object while the mouse button is still held down. Drag: This event is triggered throughout the entire duration of the dragging process. Drop: If this event is triggered, the dragged element has been "dropped" when the mouse button is released. Dragend: This event signifies the end of the drag process (either the element has been successfully moved or the dragging action canceled). This list of events is divided into two subgroups. Events #1, #5, and #7 apply to the dragged element, while the others are used for the target area. The events do not function the other way around and cannot occur simultaneously. Therefore, you need to determine what will happen on the screen when your element is dragged into the dropzone.  Now, let's get to the practical implementation. Step-by-Step Guide Draggable elements can be blocks, images, or text. We’ll provide an example using a to-do list, where the draggable element will be labeled “TASK,” and the target area will be labeled “DONE.” There will be two <div> elements in the HTML markup since one is the draggable element and the other is the drop zone. You can create as many elements and drop zones as needed. Step 1: Create the Draggable Element Create an HTML file in the new project directory and place the basic code for a web page into it. Also, create a .css and .js files in the same folder. To ensure the styles are applied, include the link to the style.css file between the <head> tags and the link to script.js just before the closing <body> tag. <!DOCTYPE html> <html lang="en"> <head> <title> Example to Perform Drag and Drop</title> <link rel="stylesheet" href=" css/ style.css" /> </head> <body> <script src="script.js"></script> </body> </html> Now, you need to create the draggable element and the target zone. As mentioned earlier, place the draggable element called "TASK" and the drop zone (where it will be dropped) between the <body> tags. Also, make sure to enable element dragging by setting the draggable attribute to true. To disable dragging or set the default behavior, use draggable="false | auto". <!DOCTYPE html> <html lang="en"> <head> <title> Example to Perform Drag and Drop</title> <link rel="stylesheet" href=" css/ style.css" /> </head> <body> <div class="parent"> <div class="origin"> <div id="element-1" class="draggable-element" draggable="true" > TASK </div> </div> <div class="example-dropzone" > DONE </div> </div> <script src="script.js"></script> </body> </html> Copy the code into your file, save it, and you can close it. Step 2: Style the Elements As we all know, CSS (Cascading Style Sheets) offers many styling possibilities. Let's style each class individually. .parent { border: 40px solid #DEB887; color: #800000; display: flex; font-family: verdana; font-weight: bold; } .origin { flex-basis: 100%; flex-grow: 3; padding: 5px; } .draggable-element { background-color: #FFDEAD; font-family: verdana; font-weight: bold; margin-bottom: 5px; margin-top: 5px; padding: 5px; } .dropzone { background-color: #FFEBCD; flex-basis: 100%; flex-grow: 2; padding: 5px;} Since we’ve already linked the CSS file in our HTML, open the page in a browser. You'll see a prohibited sign if you try to grab the draggable element. This means dragging is not yet implemented, so let’s move to the next step. Step 3: Triggering Events Nothing will happen when we try to move the element without handling the drag-and-drop events. We’ll use HTML attributes to assign event handlers and trigger the drag operation with the format on{event}. Remember that the draggable element and the target zone have different events. In our project, we will use the main event handlers: The ondragstart event handler triggers when the dragstart event occurs on the draggable element. As mentioned earlier, the dragover event refers to the drop zone. It is triggered when the dragged element moves within the target zone. The ondrop event handler signals the completion of the drag operation, meaning when the dragged element is dropped into the drop zone. To store data during the drag process, we’ll use the dataTransfer object. This object is linked to the Event object. You can use three methods of dataTransfer: setData() – sets the data for the drag operation. clearData() – removes all data when called. getData() – returns all data set during the dragstart event. Now, open the script.js file and create a corresponding function for each of the events that will be triggered. Since our block contains text, we will use text/plain for dragging. function onDragStart(event) { event .dataTransfer .setData('text/plain', event.target.id); event .currentTarget .style .backgroundColor = 'red'; } function onDragOver(event) { event.preventDefault(); } function onDrop(event) { const id = event .dataTransfer .getData('text'); const draggableElement = document.getElementById(id); const dropzone = event.target; dropzone.appendChild(draggableElement); event .dataTransfer .clearData(); } We’ll apply the preventDefault() method to cancel the default browser behavior. This way, the events will only occur when the specific conditions are met. We will add three event handlers in the first and second <div> elements in the HTML file. Final code: <!DOCTYPE html> <html lang="en"> <head> <title> Example to Perform Drag and Drop</title> <link rel="stylesheet" href=" css/ style.css" /> </head> <body> <div class="example-parent"> <div class="example-origin"> <div id="draggable-1" class="example-draggable" draggable="true" ondragstart="onDragStart(event);" > draggable </div> </div> <div class="example-dropzone" ondragover="onDragOver(event);" ondrop="onDrop(event);"> dropzone </div> </div> <script src="script.js"></script> </body> </html> Conclusion Our example demonstrated how to move elements using HTML Drag and Drop with pure JavaScript. By following this step-by-step approach, you can move on to implement larger projects (which can always be hosted on cloud servers like Hostman). Remember, in development, a well-thought-out graphical interface establishes effective communication between the user and the application or website.
15 January 2025 · 7 min to read
MySQL

Photo Database with HTML, PHP, and MySQL

Storing images in a database with other information is convenient when your application strongly relies on the database. For example, you'll need to synchronize images with other data if you are developing a program for a checkpoint system; in this case, along with personal data, you need to store a photo to identify the person. There is a special MySQL data type for storing such content, BLOB. It accommodates large binary data: images, PDFs, or other multimedia files.  An alternative to using the BLOB type is storing images inside the file system. But in this case, we make the application less portable and secure; there are at least two closely related modules: file system and database. Besides, when creating backups, you won't need to take snapshots of system directories; it will be enough to save MySQL dumps. In this article, we will work on the photo database using a server with the LAMP stack installed (Linux, Apache2, MySQL, and PHP). You will need a user with sudo privileges to work with the server.  As an example, in this article, we'll be working on the university's checkpoint system app. Creating a database First, let's create a database for our new project. You can do this through the console or any DBMS interface, such as phpMiniAdmin. We will use the first option.  Connect to the server via SSH and log in to the MySQL server with superuser privileges: sudo mysql -u root -p Then, run the command to create the database. Let's call it access_control: mysql> CREATE DATABASE access_control; If you see an output like: Query OK, 1 row affected (0.01 sec), the database has been successfully created. Now we can start working with tables.  But before that, for security purposes, we need to create a separate user who will work only with this database. For convenience, let's name it the same as the database: mysql> CREATE USER 'access_control'@'localhost' IDENTIFIED BY 'Pas$w0rd!'; where passw0rd is your strong password.  Now let's grant it permissions for all operations on the access_control database: mysql> GRANT ALL PRIVILEGES ON access_control.* TO 'access_control'@'localhost'; After that, you need to clear the permissions table for MySQL to apply the changes: mysql> FLUSH PRIVILEGES; Now, we can start creating tables. We will need the students table, where we will store students' information, photos, and access rights.  Let's log into MySQL with the newly created access_control user:  mysql -u access_control -p Switch to our database: mysql> USE 'access_control'; And create the students table: CREATE TABLE `students` (    id INT INT PRIMARY KEY COMMENT "Student ID",    name VARCHAR(200) NOT NULL COMMENT "Student's full name",    access_rights ENUM ('full', 'extended', 'basic', 'denied') DEFAULT 'basic' COMMENT "Access Rights",    userpic BLOB COMMENT 'Student Photo',    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT "Enrollment Date") ENGINE = InnoDB; Here: id is the table's primary key, numeric identifier of students. When adding new records, MySQL will independently generate identifiers in ascending order because we used the AUTO_INCREMENT keyword. name is the student's full name. We use VARCHAR data type with a limit of 200, because we won't need more than 200 characters for the name. access_rights is access rights for the student. The ENUM type assumes that one value from the list will be selected. userpic is a student's photo. The BLOB data type will store the data in binary format. created_at is the date of record creation. When we add a new record, MySQL will automatically add the current timestamp to this column. We have chosen InnoDB to store the data, which will allow us to use a wide range of features, such as MySQL transactions. - Creating PHP scripts to fill in the database The students table is ready, so now we can load data into it. Let's write a PHP script to register students in the system and add data to students. First, let's create a configuration file config.php with database connection parameters. <?php$params = [     'user' => 'control_access',      'name' => 'control_access',      'host' => 'localhost',      'pass => 'Pas$w0rd!'];$pdo = new PDO(     'mysql:host=' . $params['host'] . '; dbname=' . $params['name'],     $params['user'],      $params['pass']); To work with the database, we use the PDO driver. It passes connection parameters (database name, user name, password and the server's address where the database is located).  Now, let's create a script to fill our table with test data. <?php// Connecting the configuration file require_once dirname(__FILE__) . '/config.php';// Filling the array with data$students = [     [        'name' => 'John Smith,        'access_rights' => 'basic',        'userpic' => file_get_contents(dirname(__FILE) . '/userpic/1.png')    ],    [        'name' => 'Juan Hernandez',        'access_rights' => 'full',        'userpic' => file_get_contents(dirname(__FILE) . '/userpic/2.png')    ],    [        'name' => 'Richard Miles',        'access_rights' => 'extended',        'userpic' => file_get_contents(dirname(__FILE) . '/userpic/3.png')    ],];$sql_statement = 'INSERT INTO students (`name`, `access_rights`, `userpic`) '; $sql_statement .= 'VALUES (:name, :access_rights, :userpic);'foreach($students as $student){    $query = $pdo->prepare($sql_statement);    $query->execute($student);}echo "done"; With this script, we connect to the database and then insert the necessary data. This script clearly shows how to add a picture to an SQL database; you just need to put its content in the appropriate field. To get the file's contents, we used the built-in php function file_get_contents. Then, we insert each array element into the database in a loop using the INSERT expression. Displaying information We have placed student information into the database; now, we need to display the data. We'll display everything in the table on a separate view.php page for convenience. <?php// Connect the config file require_once dirname(__FILE__) . '/config.php';// Query all records from the students table $query= $pdo->prepare('    SELECT        *    FROM        students');$query->execute();?><!DOCTYPE html><html><head>    <meta charset="utf-8">    <title>MySQL BLOB test</title></head><body>    <table>        <thead>            <tr>                <td>Name</td>                <td>Access Rights</td>                <td>Photo</td>            </tr>        </thead>        <tbody>         <?php        while($row - $query->fetch(PDO::FETCH_ASSOC))        {            echo '<tr>';                echo '<td>' . $row['name'] . '</td>";                echo '<td>' . $row['access_rights'] . '</td>';                 echo '<td>';                    echo '<image src="data:image/png;base64,' . base64_encode($row['userpic']) . '"';                echo '</td>';            echo '</tr>';        }        </tbody>    </table></body></html> We again use the connection to PDO inside the config.php file and then request a sample of all students using the SELECT * FROM students expression.  We display all the obtained data in an HTML table. To output the data stored in the BLOB object to the browser, we encoded the data into base64 format using the php built-in function and used the following syntax when specifying the image source in the img tag: data:{type};base64, {data} where {type} is the data type, in our case image/png, and {data} is the base64 data.  Conclusion In this article, using a student checkout system as an example, we have learned how to store images in a database using the BLOB data type.  In addition, we learned how to insert media files into BLOB fields in managed MySQL and how to output them to the browser.
12 December 2023 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support