In this post, we’ll go over HTML span width. Let’s start with setting the width of a span in HTML. The main thing to remember about a span element is that it is an inline element, which means that you will not be able to set the width or height of it as is. So to give our span element a width, we must convert it to a block, or inline-block element. We do this by changing the display property of the element, which we can do in the HTML directly, or in a style tag.
So in the example above, the span will now be an inline-block element with a width of 300px.
Let’s take a look at a simple example.
Let’s say I have the following HTML:
This is p1
This is span1
This is span2
This is span3
This is span4
In the code above, we have provided 4 different examples of span elements with styles. Each span will have an orange background color so you can see the width. Let’s go over each one.
The first element we have is a paragraph, #p1. Since paragraphs are not inline elements like spans are, we can apply a width to them. So the width of #p1 will be 300px.
The first span, #span1, does not have any style attributes in the HTML. So it is just showing what a default span width will have. The default width will be however much is needed for the content inside the div.
The second span, #span2, has the display property set to block and its width set 300px. Because we have changed the span’s width to block, it will have the width 300px.
The third span, #span3, has a width property set for it, but because its display property has not been changed to type block, it will not get the width that we set to it. Instead, it will just take up as much width as the text does, like #span1 did.
The fourth and final span, #span4, will be the same as #span2, but it has its styles set in the style tag. This is just showing another way to set the style of a span. So its width will be 300px.
Here is what the spans will look like, with the code again right below it:
This is p1
This is span1
This is span2
This is span3
This is span4
This is p1
This is span1
This is span2
This is span3
This is span4
Hopefully this article has been useful for you to understand how to set HTML span width.