css inline-block div positioning - positioning

I'm trying to fix a positing issue in a responsive design.
I have a container div, containing 4 (but it could be more or less) divs that are displayed as inline-block. I would like to know how to control the number of divs per line when the page is resized (with CSS, if it's possible). For example, when 4 containees no longer fits in the container, the last one is moved to second line. I would like in that case to have 2 containees in the first line and 2 containees in the second line. I dont know how to do that. Your help would be welcomed!
EDIT:
it could also be 6 containees, in the case the layout would be:
- 1 line of 6 blocks if it fits
- 2 lines of 3 blocks
- 3 lines of 2 blocks
- 6 lines of one
the number of containees is variable. I just want to have the same number of containees per line
the html:
<div class="container">
<div class="containee"></div>
<div class="containee"></div>
<div class="containee"></div>
<div class="containee"></div>
</div>
the css:
.containee {
width:200px;
height:200px;
display:inline-block;
background-color:tomato
}
the example can be seen here : http://cssdesk.com/uGLbq
(PS : I tried to find the solution searching the web but I dont really know the good keywords related with this topic)

You can't with CSS (AFAIK).
You can do "the math" dynamically with Javascript in real time.
In your case,
you known the width of one block (in that moment),
you can easily get the window width (in that moment),
you know the number of your block (in that moment);
Simply apply ( (1) the first time you open the page, and (2) every time the number of blocks changes, or (3) the resolution changes) the algorithm in the following code:
// EXAMPLE OF INPUT
var windowWidth = 1400; // read it...
var blockWidth = 200; // read it or use const...
var numberOfBlocks = 10; // read it...
// Calculate the maximum number of blocks per row
var maxBlocksPerRow;
for (var i=0; i < numberOfBlocks; i++) {
if ( (blockWidth * (i + 1)) > windowWidth){
maxBlocksPerRow = i;
break;
}
}
// Check the highest 0 module combination while iterating backwards
var magicNumberForMatchingBlocks = 1; // if not found, it will be 1.
for (var i = maxBlocksPerRow; i > 0 ; i--) {
if ( (numberOfBlocks % i) == 0){
magicNumberForMatchingBlocks = i;
break;
}
}
alert("With " + numberOfBlocks + " blocks, each one wide " +
blockWidth + " pixels, and a window wide " + windowWidth + " pixels,
the number of blocks per row for having always
the same number of block in any row is: " + magicNumberForMatchingBlocks);
Then use that number to populate or re-arrange the elements with Javascript or better with some Javascript library like jQuery.

html:
<div class="container">
<div class="grouped">
<div class="containee"></div>
<div class="containee"></div>
</div>
<div class="grouped">
<div class="containee"></div>
<div class="containee"></div>
</div>
</div>
css:
.containee {
width:200px;
height:200px;
display:inline-block;
background-color:tomato
}
.grouped {
float:left;
}

Try this:
.container
{
min-width: 410px;
}

Give the .containee a float:left; if the page fits for 4, they will be positioned right beside each other, else, you'll have another line of divs. You can give it as well a margin-top:5px; in case you got another line, the divs of the second line won't be glued to the divs of the first line. Note that with this approach, its not obliged to have equal number of .containee in each line, if you have 4, then you re-size, you'll have 3 - 1, then 2 - 2...etc..

Related

Fill the entire area inside a big square (a div) with little squares, based on their quantity

I want to solve it just by using css3, maybe with flexbox or grid or some other similar framework.
My markup:
<div class="square">
<div class="smaller-square">
<div class="smaller-square">
<div class="smaller-square">
<div class="smaller-square">
</div>
Quantity (Q) of inner boxes I will control. Q = i2, where i = 0...N
Updated version:
As you are taking input from user, get the value of input tag using every time, when its value changed using onchange event.
HTML:
<input onchange="fillSquare()" id="quantity" type="number" min="0"/> //You can use any input type
Javascript:
function fillSquare(){
var Q = $("#quantity").val();
var i = Math.sqrt(Q); // Here I'm taking square root of 'Q' to calculate width and height of small sqaures.
$('.smaller-square').css({
"width": (100% / i),
"height": (100% / i)
});
}
Old solution:
I think calc property in CSS better suits for your requirement.
first of all make sure you've some css like below, to make them blocks.
.square{
display:block;
width: 500px; //Any number is fine, until both height and width are same
height: 500px; //Make sure you've some numbers here, as we are going to deal with width and height of smaller-square in percentages
}
.smaller-square{
display:inline-block;
float:left;
}
Now you can achieve this in two ways, One is in pure CSS (the one you asked) and also using some Javascript library.
First, CSS:
.smaller-square{
width:calc(100% / i);
height:calc(100% / i);
}
Here you have to hard-code i value, which means you know i value before executing the code.
Eg., If i=2 then,
.smaller-square{
width:calc(100% / 2);
height:calc(100% / 2);
}
width and height of .smaller-square are 50% of .square width and height.

Wrap text from bottom to top

Anybody know how I could wrap the text in reverse order, from bottom to top?
I attached an example image.
[][http://i.stack.imgur.com/RVsIG.jpg]
Instead of breaking the line after it is full and having an incomplete line at the end, I need to brake somehow from bottom to top, so bottom lines are full and top line is incomplete.
I would not recommend using exotic CSS attributes which aren't even in Chrome & Firefox yet. The best cross-browser solution is to handle this in Javascript when the document loads. Here's a sketch of how to do that:
$(function() {
$(".title").each(function(i,title) {
var width = 0;
var originalHeight = $(title).height();
var spacer = $('<div style="float:right;height:1px;"/>').prependTo(title);
while (originalHeight == $(title).height()) {
spacer.width( ++width );
}
spacer.width( --width );
});
});
Working JSFiddle is here: http://jsfiddle.net/zephod/hfuu3m49/1/
6 years later, but fret not! I have found a pure CSS solution!
Turns out you can achieve this result with flexbox, but it's not obvious or very straight forward. This is what I started out with:
I want the header to be "bottom-heavy", the same effect as you describe in the question.
I began by splitting up my string by whitespace and giving them each a <span> parent. By using flex-wrap: wrap-reverse, and align-content: flex-start. You will achieve this:
Oh no! Now the order is messed up! Here comes the trick. By reversing both the order in which you add spans to the HTML and the direction order of flex with 'flex-direction: row-reverse', you actually achieve the "pyramid-shaped" upwards overflow effect you desire.
Here is my (simplified) code, using react and react-bootstrap:
<Row className='d-flex flex-wrap-reverse flex-row-reverse align-content-start'>
{props.deck.name
.split(' ')
.reverse()
.map(word => (
<span className='mr-1'>{word}</span>
))}
</Row>
There is no general css solution for it. You must have to utilize help of any language.
This is one of the solution using PHP:
<?php
$str= "This is what I want to achieve with your help";
$str = strrev($str);
$exp = str_split($str,18);
$str = implode(">rb<", $exp);
echo strrev($str);
?>
Well, if that is depending on the text, then you can try something like a word replacer. For example
var words = "This is what I want to achieve";
var newWords.replace("what", "what <br />"); // note the line break
document.write(newWords);
Here is a fiddle for you: http://jsfiddle.net/afzaal_ahmad_zeeshan/Ume85/
Otherwise, I don't think you can break a line depending on number of characters in a line.
Wrap and Nowrap will be rendered by the client-browser, so you can not force the browser to wrap from bottom to top. but you can do that with javascript or asp.
This is not a formal solution for this problem. But see if this helps.
The HTML CODE
<div id="mydiv">
I can imagine the logic behind the code having to detect what is the last line, detect the div size, and the font size... then measure how many characters it can fit and finally go to the above line and insert the break where necessary. Some font families might make this harder, but trial and error should solve the issue once the basic code is set..
</div>
CSS:
#mydiv
{
width:1000px;
line-height:18px;
font-size:20px;
text-align:justify;
word-break:break-all;
}
Here setting the div width around 50 times that of the font-size will give you the precise result. Other width values or font values might slightly disorient the last line, giving some blank space after the last character.(Could not solve that part, yet).
JQuery:
$(document).ready(function(){
//GET the total height of the element
var height = $('#mydiv').outerHeight();
//Get the height of each line, which is set in CSS
var lineheight = $('#mydiv').css('line-height');
//Divide The total height by line height to get the no of lines.
var globalHeight = parseInt(height)/parseInt(lineheight);
var myContent = $('#mydiv').html();
var quotient = 0;
//As long as no of lines does not increase, keep looping.
while(quotient<=globalHeight)
{
//Add tiny single blank space to the div's beginning
$('#mydiv').html(' '+myContent);
//Get the new height of line and height of div and get the new no of lines and loop again.
height = $('#mydiv').outerHeight();
lineheight = $('#mydiv').css('line-height');
quotient = parseInt(height)/parseInt(lineheight);
myContent = $('#mydiv').html();
}
//get the final div content after exiting the loop.
var myString = $('#mydiv').html();
//This is to remove the extra space, which will put the last chars to a new line.
var newString = myString.substr(1);
$('#mydiv').html(newString);
});
If you already know where you want your breaks to take place just use simple HTML breaks to break your content and have it display the way you want.
<p>This is what<br/>
want to acheive with your help</p>
If you set the breaks manually (and you know where you want them to break) then create them yourself.
You could also try setting separate css width adjustments based on the dimensions of the screen you are seeing the breaking you are not liking and set an #media reference to make the div width smaller to break the text so it doesn't run unevenly across the top of certain size devices.
Use display: inline-block; on the text div.

Floating with css percentages, full-width browsing

Original question:
Okay, this is plain and simple css. But there's a bug on my site and i can't get it out !
I making a site with this design: http://cl.ly/image/1j231y2x3w07
The site i fully responsive and makes use of the css-aspect-ratio-technique:
HTML:
<div class="post small">Post that is small</div>
<div class="post big">Post that is big</div>
<div class="post tall">Post that is tall</div>
<div class="post wide">Post that is wide</div>
CSS/LESS:
.post {position: relative;}
.post:after {display: block; content: '';}
.post.small {width: calc(1/4 * 100%);}
.post.small:after {padding-top: 70%;}
.post.big {width: calc(1/2 * 100%);}
.post.big:after {padding-top: 70%;}
.post.tall {width: calc(1/4 * 100%);}
.post.tall:after {padding-top: 140%;}
.post.wide {width: calc(1/2 * 100%);}
.post.wide:after {padding-top: 35%;}
You get the gist of it.
I also make use of the excellent plugin Packery.js to keep track of floats and position. I mostly use is as a resize and animation helper.
But being fully responsive gives me a problem. For example when the browser window is 1304px wide, i get some odd height values(ex. 477.4px) due to the technique mentioned above. Because of the odd numbers i am not able to keep my grid, let alone my design.
And if the windows width is not divisible by 4 i get overlapping or 1 pixel white lines.
I've been working on this for quite some time now, and need some fresh eyes.
So, if anybody got inputs to a solution i would be very happy. Thanks :-)
The solution:
A big thanks to #ScottS – great advice !
function frontpageResize() {
// container ... duh.
var container = $('#frontpage-wrapper');
// body width.
var bWidth = window.innerWidth;
// get the pixels missing for making bWidth divisible by 20.
var divisibleBy = bWidth % 20;
// setting an alternative width.
var altWidth = Math.ceil(bWidth - divisibleBy + 20);
// what's missing?
var leftover = altWidth - bWidth;
// if body width is divisible by 20 all is peaches?
if(divisibleBy === 0) {
container.width(bWidth);
} else {
// else set the alternative width as body width and set margin-left.
container.width(altWidth).css({ "margin-left" : -leftover / 2 + "px"});
}
// relayout Packery.js
container.packery();
}
The Only Way You Will Eliminate All Rounding Issues
To get the quartering division of width's without issues, as you noted, you need a total width that is divisible by 4. To get the height divisions with the percentages you are using you need a total width that is divisible by 20 (35% of 20 = 7, a prime number; there is no other values between 1-19 that can be multiplied by 35% without a fraction being generated).
So that means you need your widths to not shoot for 100% window width, but rather the width value that is the next smallest division by 20 (and then perhaps center your display, so that the 0 to 9.5px left over become side margins through an margin: 0 auto rule).
So your theoretical calculation you need for your width value needs to use a modulus function, something like this:
#width - mod(#width, 20) //in LESS
or
width - (width%20) //in javascript
As you can see, though, the point is you would need a dynamic action that CSS does not have available natively to make it pixel perfect.

Ordering divs with javascript

I have something like this:
http://s9.postimg.org/wwizuwnq7/Untitled_1.png
And if you see, the divs (Where I marked in green) have a space of some pixel.
And i want if there is a 0-20 pixel space between divs, to order them like this:
http://s23.postimg.org/ky2htcpt7/image.png
So, i started to do this on javascript and i dont know to to continue..
var position = new Array();
$(".post").each(function(){
position[$(this).attr("id")] = $(this).offset().top - $(window).scrollTop();
});
now i have all the position of all the divs, and now i need to check where divs have a space of 0 - 20 pixel, and then i want to take down the higher block.
I not sure if this is the good way, and if now, i need another idea..
Thanks!
I managed to find a method!
var position = new Array();
$(".hblocks").each(function(){
position[$(this).attr("id")] = $(this).offset().top;
});
$.each(position, function(key, value) {
$.each(position, function(key2, value2) {
var space = value2 - value;
if (space <= 20 && space >= -20 && space != 0)
{
var finalSpace = Math.max(value, value2);
var spaceplus = space + 28;
if (finalSpace != value)
{
$("#" + key).css("margin-top",spaceplus + "px");
}
else
{
$("#" + key2).css("margin-top",spaceplus + "px");
}
}
});
});
You can do this by adding a container div around the bottom 2 blocks. That way they will always be in line, regardless of the height of either of the top two blocks. You should try not to use javascript for styling. CSS is very powerful.
Here's a fiddle: http://jsfiddle.net/kVn7x/
HTML:
<div>
<div style='height:100px;'></div>
<div style='height:200px;'></div>
</div>
<div style='clear:left'>
<div style='height:80px;'></div>
<div style='height:80px;'></div>
</div>
CSS:
div div{background:red; width:150px; display:inline-block; margin:5px; float:left; clear:none}
Can't you simply add a bottom margin to the selected element in CSS?
#element {
margin-bottom: 20px;
}
Your answer would be some king of javascript+css coding to verify height of elements .. work on em then re-arrange them.
Stop trying to figure out by yourself, try using Masonry or jQueryEqualHeight explained on CSSTrick.
What is Masonry?
Masonry is a JavaScript grid layout library. It works by placing
elements in optimal position based on available vertical space, sort
of like a mason fitting stones in a wall. You’ve probably seen it in
use all over the Internet.
This is untested but something like this should work after your code...
The idea is to continuously add 1pixel to the top margin of the problematic div until the difference between the two divs is 20px
while(position['div1'] - position['div2'] <20){
$('#div2').animate({marginTop: '+=1px'}, 0);​​​​​​​​​​​​​​​​​
}
If you want to show them directly in line as in your picture, it's even easier:
var diff = position['div1'] - position['div2']
if(diff < 20){
$('#div2').animate({marginTop: '+=' + diff + 'px'}, 0);​​​​​​​​​​​​​​​​​
}

Is there any way to select a last element in a Current row of multi-line stack in a block?

For example, i have some <ul> element with <li> blocks floated left.
If i resize my that way, that to <li> elements got place by 3 in a row. Next, i resize window (by mouse for example) and my <ul> got new width with <li> elements placing by 4 in a row for now.
So, how to select last <li> in a every row of that stack of elements, that to set them some CSS rule (margin-right for example).
So i need to know, is there any CSS selector or way to select with behavior explained here:
http://jsfiddle.net/w7PDM/12/
you'll have to calculate the last one, and it's simple.
$('button').click(function(){
$('ul').css('width','200px');
$('.current-last-of-row').removeClass('current-last-of-row');
var itemsPerRow = Math.floor(parseInt($('ul').css('width')) / 40);
//$('li:nth-child(4n+4)').addClass('current-last-of-row');
for(var i=1; i < $('ul li').length; i++)
{
if( i % itemsPerRow == 0 )
{
$('li').eq(i-1).addClass('current-last-of-row');
}
}
$('h1').text('Now, every 4 element is a "last-of-a-row"');
});​
check out the demo: http://jsfiddle.net/jun1st/hK9aZ/1/

Resources