By SAGAR on 07 Apr 2021
Sometimes you want to put HTML elements in groups, or put a wrapper around certain text so that you can select it. Learn how in this article…
Wrapping is where you wrap a certain bit of text or element in a wrapper element.
Grouping is where you put a wrapper around multiple elements.
DIV
div
stands for division, and is used to group elements together. Here is an example:
SPAN
span
's are generally used to wrap around certain bits of text (I will go into why further down). The syntax is as follows:
First of all, why would you actually want to do this in the first place? Well, there are many good reasons:
Div
By putting parts of your code into groups. Take this example:
If you were looking at this code, it would be very confusing to work out what was the content and what was other stuff. If we did this, it would make the code much more clear:
div
Chances are, you probably haven’t learned CSS yet but down the track this will be a big benefit. Let’s say you have a bunch of random elements:
What if we wanted to give all of those elements a color
of blue
? (NOTE: You don’t need remember anything about CSS from this, I’m just using it to explain my point). You would have to do it like this:
In addition, this would also style any other h1
, h2
, etc. on the page. However, we put all these elements in a group though, it becomes much easier:
This will make all the elements inside div class="style-me"
blue.
div
For example, let’s say you want to have a sidebar - instead of manually positioning all the elements of the sidebar, you can just wrap them with a div
and position that. Consider a div
as a box - when you move a box, you end up moving the stuff in it as well. If we want to move our sidebar box over to the right, doing so will also move all the stuff inside it.
span
Let’s say you have the following HTML:
What if you wanted to do something with the word awesome
? Let’s say make it red? There is no way to select it, it is just text. To select it, we can wrap it in a span
with a class: