View video tutorial

HTML width Attribute

HTML

The HTML width attribute specifies the width of an element.

Definition and Usage


➔ The width can be defined with or without the px suffix.

➔ It is recommended to use CSS to set the width in px or other units.

Syntax
//In HTML
<div>
    <canvas id="mycanvas" height="120px" width="250px" style="border:2px solid #777;background-color:#d5e5f5;">
    </canvas>
</div>

//In JavaScript
<script>
    const element = document.getElementById('mycanvas');
    element.width = 400;
</script>

Applies to

This attribute can be used on the following element.

Attribute Element
width <canvas>, <embed>, <iframe>, <img>, <input>, <object>, <video>

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML width attribute example</title>
    <meta charset="utf-8" />
</head>
<body>
    <h3>HTML width attribute example</h3>
    <p>width attribute specifies the width of an element</p>
    <div>
        <canvas id="mycanvas" height="120px" width="250px" style="border:2px solid #777;background-color:#d5e5f5;">
        </canvas>
    </div>
    <script>
        //const element = document.getElementById('mycanvas');
        //element.width = 400;
    </script>
</body>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.


Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML width attribute example</title>
    <meta charset="utf-8" />
</head>
<body>
    <h3>HTML width attribute example</h3>
    <p>width attribute specifies the width of an element</p>
    <div>
        <canvas id="mycanvas" height="120px" width="250px" style="border:1px solid #aaa;background-color:#f5f5f5;">
        </canvas>
    </div>
    <script>
        (() => {
            let canvas = document.getElementById("mycanvas");
            let ctx = canvas.getContext("2d");
            const rectWidth = 250;
            const rectHeight = 120;
            const xPos = (canvas.width / 2) - (rectWidth / 2);
            const yPos = (canvas.height / 2) - (rectHeight / 2);
            ctx.fillStyle = "white";
            ctx.fillRect(xPos, yPos, rectWidth, rectHeight);
            //ctx.beginPath();
            ctx.fillStyle = "red";
            ctx.arc(canvas.width / 2, canvas.height / 2, 40, 0, 2 * Math.PI, false);
            ctx.fill();
        })();
        // code to be executed automatically immediately
        /* (() => {
         //code goes here..
        })(); */
    </script>
</body>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.