What strategies can I use to include multiple spans within div elements without causing the code to become overly lengthy?

I'm working with 20 spans representing movie genres, each accompanied by another span that "closes" the genre when selected. The closing span has an .active class, similar to this example: https://i.sstatic.net/7CuuX.png

My version currently looks like this: https://i.sstatic.net/aFoE6.png

To achieve this, I have placed the "close" span inside the span containing the genre name, resulting in a larger span size. Is there a way to replicate the functionality in the image without adding excessive code?

Below is the HTML code snippet:

<div class="genres">
            <span>action<span class="close active">x</span></span>
            <span>adventure</span>
            <span>animation</span>
            <span>comedy</span>
            <span>crime</span>
            <span>documentary</span>
            <span>drama</span>
            <span>family</span>
            <span>fantasy</span>
            <span>history</span>
            <span>horror</span>
            <span>music</span>
            <span>mystery</span>
            <span>romance</span>
            <span>science fiction</span>
            <span>TV movie</span>
            <span>thriller</span>
            <span>war</span>
            <span>western</span>
        </div>

I initially considered adding the "close" span to every genre span individually, but this would increase span sizes significantly. Alternatively, placing these spans in separate divs would lead to bloated code.

Here are the CSS styles applied:

.genres span{        
    color: rgba(0, 0, 0, 0.87);
    display: flex;
    text-transform: capitalize;
    cursor: pointer;
    background-color: #fff;
    line-height: 3px;
    border-radius: 10px;
    padding:10px;
    font-size: 0.850rem;
    margin:2px;
    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.genres span.close{
    display: inline;
    text-transform: none;
    padding: 10px;
    margin:0;
    border-radius: 10px;
    font-size: 0.8rem;
    color: #3f51b5;
    background-color: rgba(172, 157, 157, 0.7);;
}

Answer №1

Perhaps this information can assist you further.

const genresElement = document.querySelector('.genres');
const genres = ['action', 'adventure','animation', 'comedy','crime','documentary', 'drama','family','fantasy','history','horror','music','mystery','romance','science fiction','TV movie','thriller','war','western'];
let selectedGenres = [];
let htmlToAdd = '';

genres.forEach(genre => htmlToAdd += `<span>${genre}</span>`);
genresElement.innerHTML = htmlToAdd;

genresElement.addEventListener('click', (e)=> {
  let el = e.target;
  if(el.tagName === 'SPAN')
    el.classList.contains('active') ? addRemoveGenre(el,'remove',el.textContent) : addRemoveGenre(el,'add',el.textContent);
});

function addRemoveGenre(el,action,genre){
  el.classList[action]('active');
  action === 'add' ? selectedGenres.push(genre) : selectedGenres.splice(selectedGenres.indexOf(genre), 1);
  console.log('selected genres: '+selectedGenres);
}
*{box-sizing: border-box;}
.genres {
  background: #39445a;
  font-family: sans-serif;
  padding: 1em;
}

.genres > span {
  color: #444;
  position: relative;
  display: inline-block;
  padding: 7px 10px;
  border-radius: 20px;
  margin: 5px;
  background: #e0e0e0;
  cursor: pointer;
  text-transform: capitalize;
  font-size: 14px;
}

.genres > span.active {
  background: #4050b5;
  color: #fff;
}

.active::after {
  content: 'x';
  display: inline-block;
  width: 12px;
  height: 12px;
  background: rgba(255,255,255,.5);
  border-radius: 50%;
  text-align: center;
  line-height: 12px;
  font-size: 6px;
  margin-left: 5px;
  vertical-align: middle;
}
<h2>Click the genres below.<br></h2>
<div class="genres"></div>

Answer №2

To easily add a close button to all active spans, you can use CSS only by adding the close button with ::after. No changes are needed in the HTML code.

View the working example here.

HTML:

<div class="genres">
      <span class="active">action</span>
      <span class="active">adventure</span>
      <span>animation</span>
      <span>comedy</span>
      <span>crime</span>
      <span>documentary</span>
      <span>drama</span>
      <span>family</span>
      <span>fantasy</span>
      <span>history</span>
      <span>horror</span>
      <span>music</span>
      <span>mystery</span>
      <span>romance</span>
      <span>science fiction</span>
      <span>TV movie</span>
      <span>thriller</span>
      <span>war</span>
      <span>western</span>
    </div>

Updated CSS:

body {
  background-color: rgb(1, 1, 53);
}

.genres span {
  color: rgba(0, 0, 0, 0.87);
  display: inline-block;
  text-transform: capitalize;
  cursor: pointer;
  background-color: rgb(182, 182, 182);
  border-radius: 10px;
  padding: 2px 8px;
  font-size: 0.85rem;
  margin: 2px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.genres span.active {
  background-color: blue;
  color: white;
}

.genres span.active::after {
  content: 'X';
  padding: 0 6px;
  background-color: rgb(212, 212, 212);
  color: black;
  border-radius: 50%;
  margin-left: 4px;
  font-weight: bold;
}

Answer №3

To center items within a flex container, you can utilize the CSS property align-items: center; in the parent element:

.genres span{
    align-items: center; //this is crucial
    color: rgba(0, 0, 0, 0.87);
    display: flex;
    text-transform: capitalize;
    cursor: pointer;
    background-color: #fff;
    line-height: 3px;
    border-radius: 10px;
    padding:10px;
    font-size: 0.850rem;
    margin:2px;
    font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

Answer №4

Here is a sample:

<style>
    .genres span {
        /* */
        color: rgba(0, 0, 0, 0.87);
        display: flex;
        text-transform: capitalize;
        cursor: pointer;
        background-color: #fff;
        line-height: 3px;
        border-radius: 10px;
        padding: 10px;
        font-size: 0.850rem;
        margin: 2px;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .genres span.close {
        display: inline;
        text-transform: none;
        padding: 10px;
        margin: 0;
        border-radius: 10px;
        font-size: 0.8rem;
        color: #3f51b5;
        background-color: rgba(172, 157, 157, 0.7);
    }
</style>

<body>
    <div class="genres" id="main">
        <span>action<span class="close active">x</span></span>

    </div>

    <script>
        var tag = document.createElement("p");

        const text = ['Text1', 'Text2', 'Text3'];

        for (var i = 0; i < text.length; i++) {
            var txt = document.createTextNode(text[i]);
            tag.appendChild(txt);
            var br = document.createElement("br");
            tag.appendChild(txt);
            tag.appendChild(br);
            var element = document.getElementsByClassName("genres")[0];
            element.appendChild(tag);
        }
    </script>
</body>

It uses Javascript to display the content.

Answer №5

Here is an example of how your code should be structured. Feel free to customize it further to suit your needs.

<div class="genres">
            <span>action<span class="close ">x</span></span>
            <span>adventure<span class="close ">x</span></span>
            <span>animation<span class="close ">x</span></span>
            <span>comedy</span>
            <span>crime</span>
            <span>documentary</span>
            <span>drama</span>
            <span>family</span>
            <span>fantasy</span>
            <span>history</span>
            <span>horror</span>
            <span>music</span>
            <span>mystery</span>
            <span>romance</span>
            <span>science fiction</span>
            <span>TV movie</span>
            <span>thriller</span>
            <span>war</span>
            <span>western</span>
        </div>

Please see the CSS style guide below:

 .genres span {
        color: rgba(0, 0, 0, 0.87);
        text-transform: capitalize;
        cursor: pointer;
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        border-radius: 10px;
        background: rgba(52, 62, 199, 0.87);
        display: inline;
        font-size: 9px;
        font-weight: bold;
        padding: 5px;
        margin: 0px;
    }

    span.close {
        background: white;
display: inline-block;
line-height: 1.2;
padding: 0;
margin: 0px;
width: 12px;
height: 12px;
text-align: center;
font-weight: 900;
text-transform: lowercase;
margin-left: 5px;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the power of PHP includes with nested subdirectories

Hello, I recently configured my web server to run all .html files as .php files, allowing me to utilize the php include function, which has been very beneficial. However, I have various subdirectories with multiple files in each one. Homepage --banners ...

Employ a distinct styling approach for Chrome and Mozilla with only utilizing a single style

This is the CSS style defined in a PHP file for an Element line-height: 120px; display: list-item; display: -moz-inline; list-style: none; If the browser is Chrome, I want it to show display: list-item, and if it's Mozilla, then display: inline. Th ...

Node.js causing issues with executing jQuery front-end code properly

I created an automatic image scroller div consisting of a ul with small images. The aim is to have a basic scroller that starts running once the page loads. It functions perfectly when I test the code (HTML, CSS, and a JS file with jQuery) locally in a bro ...

A step-by-step guide on uploading a CSV file in Angular 13 and troubleshooting the error with the application name "my

I am currently learning angular. I've generated a csv file for uploading using the code above, but when I try to display it, the screen remains blank with no content shown. The page is empty and nothing is displaying Could it be that it's not ...

Tips for creating a custom Menu with content overflow in a single direction

What is the goal of this task? I have developed a custom Menu in my application with 8 options. There is a need to dynamically disable certain menu options based on specific conditions (e.g. disabling the last 4 options). When a user hovers over a disable ...

PHP 7.2 does not allow code to reference previously set sessions

Currently, I am utilizing sessions to transmit either a success or error message to the subsequent site by employing an included PHP file (message.php) to exhibit said message. Unfortunately, for unknown reasons, the message.php file is unable to referenc ...

Inconsistencies with Handlebars adding forward slashes "/" to page addresses are causing confusion among users

In my project, I have 10 unique .handlebars files that are being called using express GET methods as shown below: app.get('/pagename1', function(req, res, next) { res.render('page1'); }); app.get('/pagename2', function(req ...

What's the reason why Angular stops flickering with the use of "/" in href?

Recently, I've come across a peculiar issue in one of my web applications while using Angular's routeProvider as a template engine. The app functions properly, but the behavior seems inexplicable to me. The problem arises during page transitions ...

Set the <img> source to link to a PHP webpage

I store all my images in a secure directory inaccessible to normal users. The filenames are generated randomly, so I want to keep the path and names of the files hidden. Currently, my img element looks like this: <img src="get_image.php?id=1"> This ...

Using jQuery to define and apply style attributes

I'm currently working on a script that will add a left and right border to a button in a row of 3 buttons when that specific button is clicked. The goal is for the borders to remain while the button is active, and disappear once another button is clic ...

Safari has a unique feature where margins are not factored into the scroll width calculation

I am facing an issue with a container that scrolls horizontally. Inside this container, there are multiple items and I have added a margin to the last item on the right. However, in all browsers except for Safari, the margin is included in the scroll width ...

Using CSS and JavaScript to hide a div element

In my one-page website, I have a fixed side navigation bar within a div that is initially hidden using the display:none property. Is there a way to make this side nav appear when the user scrolls to a specific section of the page, like when reaching the # ...

The issue with Open Sans and sans-serif fonts not rendering properly in all web browsers

I am having trouble with websites that use the Open Sans font appearing with a strange handwriting style. I'm not sure where this issue is originating from. Here are some things I have tried: Using In-Private browsing Disabling all extensions Testin ...

Optimal method for arranging Vue components

When deciding where to position a child element, should it be done within its own CSS scope or from the parent? In the scenario provided below, would it be more effective to use margin-left: auto; on the parent element or the child element (both options a ...

What is the best method for styling the "body" of multiple pages in a React.js application to prevent them from overlapping?

Hello everyone, After attempting different approaches in numerous ways, I have turned to the experts here who are sure to have the answer to this simple problem. The issue at hand is that when I try to apply background images and other properties to the ...

The video is not displaying on the webpage when connected locally, but it appears when the source is a URL

Recently, while practicing some basic tasks on a cloud IDE called Goorm, I encountered an issue with displaying a video on a simple webpage. The EJS file and the video were located in the same folder, but when I set the src attribute of the video tag to "m ...

Step-by-step guide on retrieving news_id and displaying it in an alert when an item

How can I retrieve the item ID when it is clicked in a Listview to display the specific news_id in an alert? Below is the HTML code snippet for my page: <body> <div data-role="page" id="taxmanhomepage" data-theme="e"> <div data-role="h ...

Struggling with jquery's addClass method when trying to apply a class to

Below is a sample tr: <tr> <td><input type="text" class="ingredient required" name="ingredient"></td> <td><input type="number" class="amount required" name="amount" ></td> <td><input type="number" c ...

What is the best way to submit your CSS feature suggestions?

Is there a designated platform for submitting CSS feature requests officially? I am interested in proposing the addition of an 'inset' keyword to the text-shadow property for creating inset text shadows. This enhancement seems consistent with th ...

Issue with CSS on various mobile devices

Using this CSS to display a fixed part at the bottom of the mobile screen, I noticed that it works well on the Samsung Grand Prime but appears narrower on the Samsung J7 Max. Here is the code snippet and images for reference: .footer { position: fixed ...