Categories
HTML Web development

HTML width Attribute

Learn how to use the HTML width Attribute.


HTML width Attribute

The HTML width attribute defines the width of the element (in pixels).

The HTML width attribute can be used on the following elements:

Example1:

For the <canvas> element:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="100" height="100" style="border:1px solid #333">
</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#0a9396";
ctx.fillRect(25, 25, 50, 50);
</script>

</body>
</html>

Output:


Example2:

For the <iframe> element:

<!DOCTYPE html>
<html>
<body>

<iframe src="https://www.lenastanley.com/" width="640" height="200">
</iframe>

</body>
</html>

Output:


Example3:

For an <img> element:

<!DOCTYPE html>
<html>
<body>

<img src="https://lenadesign.org/wp-content/uploads/2019/12/avatar.jpg" alt="avatar" width="320" height="240">

</body>
</html>

Output:

avatar

Example4:

For an <input> element:

Note: For input elements, you can use the width attribute only with <input type=”image”>.

<!DOCTYPE html>
<html>
<body>

<form action="">
  <label for="fname">First name: </label>
  <input type="text" id="fname" name="fname"><br><br>
  <label for="lname">Last name: </label>
  <input type="text" id="lname" name="lname"><br>
  <input type="image" src="https://lenadesign.org/wp-content/uploads/2021/06/submit-button.png" alt="Submit" width="100" height="100">
</form>

</body>
</html>

Output:





Example5:

For the <video> element:

<!DOCTYPE html> 
<html> 
<body> 

<video width="640" controls>
  <source src="https://videos.files.wordpress.com/lFj3lsG4/valentines-day-movie_dvd.mp4" type="video/mp4">
</video>

</body> 
</html>

Output:


Enjoy coding!

Read also:

HTML audio tag

HTML style Attribute

HTML tabindex Attribute