How to Set Width and Height of Span Element using CSS ?
Last Updated :
05 Feb, 2024
The <span>
tag is used to apply styles or scripting to a specific part of text within a larger block of content. The <span>
tag is an inline element, you may encounter scenarios where setting its width and height becomes necessary. This article explores various approaches to set the width and height of a <span>
element using CSS.
Method 1: Using Inline Styles
The basic method is to set the width and height of a <span>
element using inline styles directly within the HTML tag.
In this example, the style attribute is used to set the width to 200px and the height to 100px. Additionally, display: inline-block; is applied to allow the <span> to have width and height properties.
Example:
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
Set Width and Height of
Span with Inline Styles
</ title >
</ head >
< body >
< span style="
width: 200px;
height: 100px;
display: inline-block;
background-color: rgb(6, 104, 42);">
GeeksforGeeks
</ span >
</ body >
</ html >
|
Output:
Method 2: Using CSS Classes
To apply the same width and height styles to multiple <span> elements, you can define a CSS class and then use that class in your HTML.
Here, the CSS class .resizable-span is defined with the desired width, height, and other styles. Each <span> with the class resizable-span will inherit these styles.
Example:
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
Set Width and Height of
Span with Inline Styles
</ title >
< style >
.resizable-span {
width: 200px;
height: 100px;
display: inline-block;
background-color: rgb(6, 104, 42);
}
</ style >
</ head >
< body >
< span class = "resizable-span" >
GeeksforGeeks
</ span >
</ body >
</ html >
|
Output:
Method 3: Using Flexbox
Flexbox is a powerful layout model in CSS, and it can be utilized to set the width and height of a <span> element while allowing for more complex layouts.
In this example, a <div> with the class flex-container is used as a flex container, and the <span> elements within it are given the class resizable-span. The display: flex; property on the container enables the use of Flexbox layout.
Example:
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< title >
Set Width and Height of
Span with Inline Styles
</ title >
< style >
.flex-container {
display: flex;
}
.resizable-span {
width: 200px;
height: 100px;
background-color: green;
color: white;
}
</ style >
</ head >
< body >
< div class = "flex-container" >
< span class = "resizable-span" >
Span 1
</ span >
< span class = "resizable-span" >
Span 2
</ span >
</ div >
</ body >
</ html >
|
Output:
Share your thoughts in the comments
Please Login to comment...