flexible style class in css

Currently, I am facing an issue where I need to display a variable number of items with a uniform margin setting that changes across the set.

In simple terms, if I have a set like [1,2,3,4,5], it would look like this:

1        2        3        4        5

If the number of items doubles, they should still occupy the same amount of space:

1   2   3   4   5   6   7   8   9   10

I have come up with some solutions, but what struck me was the idea of using a css-class (since the margin is consistent) to standardize the layout. It would be great if I could dynamically update the class to achieve this effect. However, I haven't found any information on how to do this. For instance, if the initial margin in the first example is margin-right: 10px;, then changing the class through something like

.myclass.setProperty('margin-right', '5px');
would modify the margin property for all elements assigned to that class.

Currently, I'm using a class for shared behavior and setting individual styles for each element, which can be quite laborious:

for (var i in mynumbers) {
    mynumbers.style.marginRight = new_margin;
}

Is there a way to dynamically change a class or if you have any suggestions on how to improve this approach? Your input and ideas are greatly appreciated. Thank you for taking the time to read and consider this problem.

Answer №1

Just when you thought you've seen it all, here's another example showcasing the power of the flex layout:

.container {
  display: flex;
  border: 1px solid;
  justify-content: space-between;
}
<h2>5 elements in a line with equal width gaps</h2>
<div class="container">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>

<h2>10 elements in a line with equal width gaps</h2>
<div class="container">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
  <span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>

If your browser supports the feature, you would see something like this:

Check out browser compatibility to make sure your project runs smoothly.

EDIT: Here's an additional use case that may catch your interest, even though it wasn't specifically asked for:

.container {
  display: flex;
  border: 1px solid;
  justify-content: space-between;
}
.container:before, .container:after {
  content: '';
  width: 0;
}
<h2>5 elements in a line with equal width gaps</h2>
<div class="container">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>

<h2>10 elements in a line with equal width gaps</h2>
<div class="container">
  <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
  <span>6</span><span>7</span><span>8</span><span>9</span><span>10</span>
</div>

If your browser supports the feature, you would see something like this:

The beauty of this setup is that space is distributed equally not just between elements, but also includes both ends of the container. Plus, the code couldn't be simpler!

Answer №2

If you're looking to streamline your table layout, consider using table-layout: fixed. This CSS property allows the browser to calculate the width of each column in the first row based on the total number of columns present in the table.

.custom-table {
    display: table;
    table-layout: fixed;
    width: 100%;
}

.custom-table > span {
    display: table-cell;
    text-align: center;
}
<div class="custom-table">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>4</span>
    <span>5</span>
    <span>6</span>
    <span>7</span>
    <span>8</span>
    <span>9</span>
</div>

<div class="custom-table">
    <span>1</span>
    <span>2</span>
    <span>3</span>
    &lt;span>4&lt;/span>
    &lt;span>5&lt;/span>
</div>

Answer №3

Absolutely, it is indeed possible to change a class's property. However, it is important to note that modifying a class's property can trigger the browser's renderer to reevaluate the entire layout of the page in order to understand how the class modification impacts the overall design. This means that if you intend to adjust your margin-right property in a way that involves animation, the performance might be affected based on the intricacy of your webpage.

<html>
<head>
<style>
.thing {
    display: inline-block;
    width: 20px;
    height: 20px;
    background: #f00;
}
</style>
</head>
<body>
<div>
    <div class="thing myClass"></div>
    <div class="thing myClass"></div>
    <div class="thing myClass"></div>
    <div class="thing myClass"></div>
    <div class="thing myClass"></div>
    <div class="thing myClass"></div>
</div>

<div>
<button id="doit">Make bigger</button>
</div>
</body>
<script>
var styleTag = document.createElement("style"),
    styleSheet, index, cssRule, style;

// Create a <style> tag that will hold our CSS rule
document.head.appendChild(styleTag);
styleSheet = styleTag.sheet;

// Insert an empty .myClass rule into the style sheet
index = styleSheet.insertRule(".myClass {}", styleSheet.cssRules.length);

// Get the 'style' object from the rule. This is nearly identical to elem.style
cssRule = styleSheet.cssRules[index];
style = cssRule.style;

// Sets .myClass { margin-right: 5px; }
style.marginRight = "5px";

// Demo to show that it works when you click a button
document.querySelector("#doit").addEventListener("click", function() {
    style.marginRight = "20px";
});

</script>
</html>

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

When trying to call a function inside jQuery's $.post, undefined is not recognized as an object

My attemptSearch function utilizes jQuery $.post to retrieve JSON results, but I'm encountering an error The error states: Undefined is not an object This error occurs on the call this.getSearchResults.bind(this) Interestingly, I have a simi ...

Encountering an Error While Trying to Add Typescript Support to Create React App Using Yarn

Encountering an issue while setting up a new Typescript/React project. Here's the error message: Installing template dependencies using yarnpkg... yarn add v1.22.19 [1/4] Resolving packages... [2/4] Fetching packages... error <a href="/cdn-cgi/l/em ...

Is it possible for me to scrape an HTML code snippet directly from a browser?

How can I extract specific content from an HTML code block using only JS or jQuery on a browser? Below is the code I am working with: <ul> <li>New York</li> <li>London</li> <li>Madrid</li> <li&g ...

Issue arises when trying to utilize Ajax on the Fancy Box overlay button click and the functionality does not perform as

Hey there! I've got a bit of a silly question for you. So, I'm pretty new to Ajax and fancy box. I've been using fancy box on one of my pages, and it's been working well so far. The issue I ran into was when I tried to make an ajax call ...

Why is it necessary in JavaScript to reset the function's prototype after resetting the function prototype constructor as well?

Code is often written in the following manner: function G() {}; var item = {...} G.prototype = item; G.prototype.constructor = G // What is the purpose of this line? Why do we need to include G.prototype = item before resetting the prototype? What exact ...

What is the process of relocating JSON and JS code from within an HTML file to external files?

My goal is to separate JSON and JavaScript code from the HTML file by moving them into external files. The examples shown below were part of a test I conducted to verify that the data was being successfully imported. As I begin to include real data, the J ...

What could be the reason for my http request failing to receive a response?

I have successfully implemented multiple routes in my API, but I am encountering issues with the comment system. I am not receiving any response when accessing the URL (node backend) or using Postman. While my server JS code works for POST requests, teams ...

Sorting a parent array in AngularJS using a child array's Date field as the basis

I have an array of arrays of objects with the following structure: parentArray = [ [{id:1, date:1505020200000}, {id:4, date:1505020200000 }], [{id:2, date:1504681500000}], [{id:3, date:1504671000000}, {id:20, date:1504671000000}] ] Each nested array cont ...

When I submit a form with an empty date input field, the Datepicker is sending a 0000-00-00 date

[I am experiencing an issue with my date input field. When I submit without entering any value, the date on the view page shows as 0000-00-00 instead of being empty or blank.] <div class="col-sm-3 col-sm-offset-1"> <div class="input-group"& ...

jQuery is in a constant state of indecision when it comes to determining the best way to manage buttons

A straightforward scenario. When a checkbox is checked, it activates a disabled button. Unchecking the box disables the button again. Sample Code: jQuery -> $('#subscribe_button').attr('disabled','disabled') $("[name= ...

Protractor end-to-end testing: Verifying page refresh functionality after clicking, with updated data

As a relatively new protractor e2e testing user, I am facing a challenge with testing a non-angular (knockout) page. The specific test case involves a kendo grid that initially loads with default data, but when a checkbox is clicked, it should reload with ...

What is the solution to prevent angular-material components from covering my fixed navbar?

After creating a navbar using regular CSS3, I incorporated input fields and buttons from angular material. However, my sticky navbar is being obscured by the components created with angular material. Here is the CSS for the navbar: position: sticky; top: ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

I received a single lengthy string as a response from an API request, and now I need to convert it into an array. The string contains values that are separated by commas. Can someone suggest the most efficient method

I am currently dealing with data retrieved from an API where some keys have values formatted in a specific way. The values of these keys are structured as arrays, but the array itself contains one lengthy string. Here is an example: "key_one&quo ...

Tips for dynamically modifying style mode in Vue.js

I am looking to implement a feature where the style can be changed upon clicking a button. In my scenario, I am using Sass/SCSS for styling. For example, I have three different styles: default.scss, dark.scss, and system.scss. The code for dark.scss look ...

Performing operations in between each subscription using RxJS

I have successfully created an angular pipe that converts text into spoken words. Currently, I am working on implementing a feature where the user can view the sentence being spoken while the audio is playing, instead of after it has finished (which is ho ...

Retrieving a channel using its unique ID and then sending a message directly into it

I am attempting to retrieve a channel by its ID and then send a message to it, but I keep encountering an error when running the code. ERROR: Error sending message to welcome channel.: TypeError: Cannot read properties of undefined (reading 'send&apos ...

Developing a Customized Modal with Backbone.js

As a newcomer to Backbone, I have been trying to create a Modal in my application by setting up a base Modal class and then extending it for different templates. However, despite conducting some research, I haven't been able to find a solution that fi ...

Conceal mobile button

Welcome to my website: Is there a way to hide the button on mobile phones? I want to create different buttons specifically for mobile devices. Below is the HTML code for the buttons. HTML <a href="http://site9171756.91.webydo.com/Info.html" target="p ...

"Enhancing Your Website with a Preloader Loading GIF: Step-by-Step Guide

Can anyone assist me in implementing a preloader with a 'loading' gif image on my website that will display for a maximum of 5 seconds before the site fully loads? I've attempted various methods without success, so any help would be greatly ...