HTML - width Attribute



The width of an element can be specified in pixels or as a percentage of its parent container using the HTML width attribute, which is frequently used with elements like pictures, tables, and table cells. It is essential for managing the organization and presentation of content on a web page.

Web developers may assure consistent and responsive design by defining the width attribute, making it an important tool for achieving desired visual aesthetics and ensuring content fits inside designated areas, improving user experience. However, CSS is frequently chosen over fixed width properties for flexible site design.

Syntax

Following is the syntax of the width attribute −

<element width = " " >

Where width should be in the pixel.

Example

In the following example, we are creating an HTML document and using the width attribute on an <img> tag.

<!DOCTYPE html>
<html>
<body>
   <h1>The img tag with width attribute</h1>
   <img src="https://www.tutorialspoint.com/images/logo.png?v2" alt="Logo" width="400" height="100">
</body>
</html>

On running the above code, the output window will pop up displaying the img on the webpage.

Example

Considering the another scenario, where we are going to use the width attribute with the embed tag.

<!DOCTYPE html>
<html>
<body>
   <h1>The embed height and width attributes</h1>
   <embed type="image/jpg" src="https://t3.gstatic.com/images?q=tbn:ANd9GcRFOuSwoPG5luSDx4onb42RzGz8EoCcjqqed6dDOpjYFTJ5dG01" width="200" height="100">
</body>
</html>

When we run the above code, it wil generate an output consisting of the image displayed on the webpage.

Example

Let's look at the following example, where we are going to use the width attribute with the canvas tag.

<!DOCTYPE html>
<html>
<body>
   <h1>width attribute with Canvas element</h1>
   <canvas id="myCanvas" width="200" height="100" style="border:1px solid"></canvas>
   <script>
      const c = document.getElementById("myCanvas");
      const ctx = c.getContext("2d");
      ctx.fillStyle = "#64f56e";
      ctx.fillRect(60, 10, 80, 80);
   </script>
</body>
</html>

On running the above code, the output window will pop up displaying the canvas on the webpage.

Example

Following is the example, where we are going to use the width attribute with the object tag.

<!DOCTYPE html>
<html>
<body>
   <h1>width attribute with object element</h1>
   <object data="https://www.tutorialspoint.com/images/logo.png?v2" width="300" height="100"></object>
</body>
</html>

When we run the above code, it will generate an output consisting of the image displayed on the webpage.

html_attributes_reference.htm
Advertisements