Can flexbox be constrained to a grid while wrapping text?

Admiring the way this design wraps seamlessly while still maintaining aligned boxes on both sides, creating a visually appealing and fully utilized space.

<head>
<style>
* {
  padding: 0px;
  margin: 0px;
  text-transform: none;
  font-style: normal;
}

p {
  display: flex;
  flex-wrap: wrap;
  width: 200px;
}

i {
  flex: 1;
  padding: 5px;
  margin: 2px;
  background: #ddd;
  text-align: center;
}
</style>
</head>
<body>
  <p>
    <i>foo</i><i>hello</i><i>congratulations</i><i>forward</i><i>interesting</i><i>place</i><i>walk</i><i>to</i><i>anyplace</i><i>next</i><i>sophisticationism</i>
  </p>
</body>

Utilizing a variety of terms to efficiently occupy available space by cleverly aligning them within each row, achieving a harmonious balance between small and large words.

Your task now involves transforming each box into equal-sized rectangles that adhere to a grid-like structure. This will result in a neat layout where boxes are positioned within a predefined square grid, ensuring a clean and consistent appearance across rows through the utilization of FlexBox.

<head>
<style>
* {
  padding: 0px;
  margin: 0px;
  text-transform: none;
  font-style: normal;
}

p {
  display: flex;
  flex-wrap: wrap;
  width: 220px;
}

i {
  width: 50px;
  height: 50px;
  padding: 5px;
  margin: 2px;
  background: #ddd;
  text-align: center;
}

.l {
  width: 114px;
}
</style>
</head>
<body>
  <p>
    <i>a</i><i>a</i><i>a</i><i>a</i><i class='l'>long</i><i>a</i><i class='l'>long</i><i>a</i><i class='l'>a</i><i class='l'>long</i><i>a</i><i>a</i><i>a</i><i>a</i><i>a</i><i>a</i><i>a</i>
  </p>
</body>

To summarize, the objective is to arrange fluid text content in a manner that fills each row completely while ensuring each rectangular block conforms to the dimensions of an individual square. The intention is to create a cohesive visual display with blocks that neatly fit into a predetermined square grid, all achieved through the strategic use of FlexBox or CSS techniques.

Curious about how this feat can be accomplished effectively while maintaining content flow and adhering to a strict grid-based layout? Let's explore the possibilities together.

Answer №1

Give it a shot (I typically split 1-3 words based on length as explained here )

function displayContent(n) {
  text.innerHTML = '<p>' + separateWords(text.innerText,n).map(line=> {
    if(line.length==2 && line[0].length<n && line[1].length<n) {
      // case for two short words
      return `<i class='long'>${line[0]}</i><i class='short'>${line[1]}</i>`
    } else {
      return line.map(w=>`<i class='${w.length<9 ? 'short':'long'}'>${w}</i>`).join('')
    }
  }).join('') + '</p>';
}


function separateWords(str,n) {
  let z=0, b=[], r=[], w=str.split(' ');
  let s = w.map(v => v.length < n ? 1 : 2);

  s.map((v,i)=>( 
    z+v>=4 ? (r.push(b),z=0,b=[]) : 0,
    z+=v, b.push(w[i]) 
  ))

  return b.length ? r.concat([b]) : r;
}


displayContent(9) // 9 is min number of letters for long words;
.short {
  flex-basis: 64px;
  flex-grow: 1
}

.long {
  flex-basis: 140px;
  flex-grow: 2
}

* {
  padding: 0px;
  margin: 0px;
  text-transform: none;
  font-style: normal;
}

p {
  display: flex;
  flex-wrap: wrap;
  width: 260px;
}

i {
  flex: 1;
  padding: 5px;
  margin: 2px;
  background: #ddd;
  text-align: center;
}
<div id="text">a aaa foo hello congratulations forward interesting place walk to anyplace next sophisticationism aa bb cccccccccc ddd</div>

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

Load data into a table in HTML after a successful jQuery event

I'm facing an issue with populating an HTML table dynamically. Below is the structure of my HTML table: <table class="flexme" id="table" border="1"> <thead> <tr> <th width="100">Usuario</th> <th wid ...

Updating an array with complex values in React using the useState hook in

I am working with a long array where I need to update the quantity under the misc array for each person. Each person in the array has a list of miscellaneous items, and each of those items can have their own array with quantities that need to be updated. T ...

Developing an interactive Vue component that is able to be modified using custom properties within the HTML code

I'm a VueJS beginner and I'm working on creating a custom ul component for a webpage. I want this component to be populated and updated using custom props in the HTML, allowing other developers to easily use, update, and add to the component with ...

Storing and accessing formatted text in MongoDB: A comprehensive guide

I recently started working with MongoDB for my personal blog site development. I am facing an issue where the blog post, when saved as a document in the MongoDB database, loses all of its formatting and appears as a single long paragraph. I'm seeking ...

Stagnant updates in component's styling

I have a list box style stored in the component's data. It is bound to a listbox element. One of the styles within it is position: absolute. My goal is to position the box directly below the input element. To achieve this, I am trying to dynamically m ...

What is the best way to securely and efficiently load JSON data from different websites?

Currently, I am developing a user script/extension for Chrome and attempting to retrieve JSON data from "a particular website." Here is the method I used: $.get( "http://cloud.hartwig-at.de/~oliver/superuser.json", function( data ) { console.log( ...

Technique for transferring information between properties of a class instance within an Express server's architecture

I am in the process of developing a monitoring server for a library using Express. My goal is to create different routers and routes, while also being able to access functions and variables from the monitor-server class. Currently, I have passed the ' ...

Using Rails AJAX to dynamically load partials without the need to submit

Imagine creating a dynamic page layout with two interactive columns: | Design Your Pizza Form | Suggested Pizzas | As you customize your pizza using the form in the left column, the right column will start suggesting various types of pizzas based on your ...

Preventing FlatList from scrolling when re-sizing

Resizable from the re-resizable package is causing my Flatlist not to scroll properly. Despite having enough elements to trigger scrolling, it fails to do so when the resizable element is present. This issue does not occur when the resizable element is rem ...

Vue - Embedding <div> elements in a recursive manner

I am attempting to recursively add a div element that includes a button in the following manner: <div v-for= "column in 25": key="column.id" class ="columna"> <div v-for="row in 10": key="row.id" ...

Bootstrap icon issue: square displaying instead of the intended icon

I am currently in the process of creating a responsive website using Bootstrap 3. I have successfully downloaded and imported Bootstrap 3 into the root directory of my website. However, I have encountered an issue where the icon does not display correctly ...

Troubleshooting issues with AngularJS $watch not triggering properly

Even though Deep watch has been activated in the factory, it is not triggering. What steps can be taken to resolve this issue and ensure that an event is triggered when the 'name' value changes? Javascript Code: var app = angular.module('a ...

Javascript Flickering Effect in HTML5

Currently, I am in the process of creating a simple game using javascript without jQuery. However, I am facing an issue with flickering on the canvas due to the clearing command. After researching solutions online, I came across suggestions for implementin ...

What is the best way to position a div on the left side when it's large and move it to the

In my coding, there is a particular div element: <div id="UnitInfoDiv" class="form-group row hidden"> <div id=@UnitPartialViewHtmlId class="row"></div> <div class="row"> <div class="col-md-6"> Is ...

What is the reason for WInJS being incorporated automatically when developing for Windows 8 in Cordova?

We are currently in the process of developing an application using AngularJS specifically targeting Windows 8. During this development phase, I observed that the generated Visual Studio project included WinJS as a reference even though we were not utilizin ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Combine less files in webpack to generate a single minified CSS output file

Can webpack be used to combine multiple less files into one minified CSS file? I'm having trouble setting different output paths for my files. How can I make my CSS file output to './assets/stylesheets/bundle/' instead of './assets/ja ...

Pressing a button meant to transfer text from a textarea results in the typed content failing to show up

Having trouble with a custom text area called a math field. I'm currently interning on a project to build a math search engine, where users can input plain text and LaTeX equations into a query bar. The issue I'm facing is that sometimes when th ...

Unable to execute PHP files using Node.js

I have been working on a Node.js web application hosted on a Heroku server. The issue I am facing is related to an AJAX request in my JavaScript code that sends a GET request to a PHP file on the server. Interestingly, this request works perfectly when I r ...

Firing the ng-change Event via JavaScript Code

I am attempting to programmatically trigger an ng-change event using JavaScript. The specific element I am working with is the following: <select ng-model="user.siteId" name="siteSelect" ng-change="user.setSelectedSite(user.siteId)" class="ng-pristine ...