dynamic layout with different heights, but in a pattern - php

I'm not sure if this is possible, but I'm trying to create a layout like so:
The elements are <div>'s with text inside, coming from a PHP foreach loop.
While being pulled from the database, there is an if conditional that can add a class, where I can can control the width/height of the element. This will make the element larger.
I've looked into CSS Grid & Flexbox, and can't see a solution. The amount of larger boxes can change from page to page, but should always keep the same pattern.
I'm wondering if the best solution would be to somehow re-arrange the array in PHP to re-order the output of the elements.

I've really tried to find a solution for this with CSS Grid, but unfortunately I've come only on possibilities which don´t make the whole thing dynamic as you might want. But I think there are currently no other options - if someone knows a way, please correct me. ;)
According to my knowledge, there is also currently no selector in css that allows you to accurately address every second element of a class, which unfortunately makes it more complicated.
In my first solution, I have built on the :nth-child(even) selector. For this approach the element with the class you want to address must be the in the right order to the parent element, so that the index is correct. Thereby you would have to adjust the PHP code, so that the larger elements already get in the right place in the HTML output.
For the second solution (which I like much less), I tried to build the whole thing on the general sibling combinator selector. With this I address all existing elements on the page individually like: .class ~ .class = second element or .class ~ .class ~ .class = third element. As a result, the PHP code would not have to be adjusted and you get "more flexibility" on this part, but you would be limited in the number of elements per page, since the settings for them would be fixed in the CSS code.
Here now the two solutions:
1. The :nth-child(even) way
.grid {
display: grid;
height: 100%;
width: 100%;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 1fr;
grid-gap: 20px;
grid-auto-flow: row dense;
}
.grid__item--large {
grid-column: -3 / span 2;
grid-row: span 2;
}
.grid__item--large:nth-child(even) {
grid-column: 1 / span 2;
}
/* just for the snippet styling */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
margin: 20px;
}
.grid__item {
min-height: 200px;
background: gray;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
color: white;
}
.grid__item--large {
min-height: 400px;
}
/* --- */
<div class="grid">
<div class="grid__item grid__item--large">1</div>
<div class="grid__item">2</div>
<div class="grid__item">3</div>
<div class="grid__item">4</div>
<div class="grid__item">5</div>
<div class="grid__item grid__item--large">6</div>
<div class="grid__item">7</div>
<div class="grid__item">8</div>
<div class="grid__item">9</div>
<div class="grid__item">10</div>
<div class="grid__item grid__item--large">11</div>
<div class="grid__item">12</div>
<div class="grid__item">13</div>
<div class="grid__item">14</div>
<div class="grid__item">15</div>
<div class="grid__item grid__item--large">16</div>
<div class="grid__item">17</div>
<div class="grid__item">18</div>
<div class="grid__item">19</div>
<div class="grid__item">20</div>
</div>
2. The "general sibling combinator" way
.grid {
display: grid;
height: 100%;
width: 100%;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 1fr;
grid-gap: 20px;
grid-auto-flow: row dense;
}
.grid__item--large {
grid-column: -3 / span 2;
grid-row: span 2;
}
.grid__item--large ~ .grid__item--large {
grid-column: 1 / span 2;
}
.grid__item--large ~ .grid__item--large ~ .grid__item--large {
grid-column: -3 / span 2;
}
.grid__item--large ~ .grid__item--large ~ .grid__item--large ~ .grid__item--large {
grid-column: 1 / span 2;
}
/* just for the snippet styling */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
margin: 20px;
}
.grid__item {
min-height: 200px;
background: gray;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
color: white;
}
.grid__item--large {
min-height: 400px;
}
/* --- */
<div class="grid">
<div class="grid__item">1</div>
<div class="grid__item grid__item--large">2</div>
<div class="grid__item">3</div>
<div class="grid__item">4</div>
<div class="grid__item grid__item--large">5</div>
<div class="grid__item">6</div>
<div class="grid__item">7</div>
<div class="grid__item">8</div>
<div class="grid__item">9</div>
<div class="grid__item grid__item--large">10</div>
<div class="grid__item">11</div>
<div class="grid__item">12</div>
<div class="grid__item">13</div>
<div class="grid__item">14</div>
<div class="grid__item">15</div>
<div class="grid__item grid__item--large">16</div>
<div class="grid__item">17</div>
<div class="grid__item">18</div>
<div class="grid__item">19</div>
<div class="grid__item">20</div>
</div>
I hope that can help somehow. :)

hope to help you.
var row=5; // total row layout
var count=0;
var strLayout='';
for(var i=0;i<row*2;i++){
if(count%3==0){
strLayout +='<div style="float:left;width:100px;height:100px;"><div style="float:left;width:40px;height:40px;margin: 5px;;background:black"></div>';
strLayout +='<div style="float:left;width:40px;height:40px;margin: 5px;;background:black"></div>';
strLayout +='<div style="float:left;width:40px;height:40px;margin: 5px;;background:black"></div>';
strLayout +='<div style="float:left;width:40px;height:40px;margin: 5px;;background:black"></div></div>';
}else{
strLayout +='<div style="float:left;width:90px;height:90px;margin: 5px;background:black"></div>';
}
if (count==3){
count=0;
}else{
count++;
}
}
$('#layout').html(strLayout);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="layout" style="float:left;width:200px;background:white">
</div>

Related

Equal heights different width layout for dynamic image gallery

am working on a codeigniter website and currently trying to achieve a layout like this where i have equal heights for all images in row but different widths.
My images are stored in a MYSQL database with url paths pointing to the directory where they are located. I have also stored their heights and widths (the height and widths are stored in pixels).
Here is the sql for fetching the contents in PhotoController
$data['data'] = $this->model
->select('photo_path, photo_height, photo_width')
->get()
->getResultArray();
Then in Home view, here is what i have so far. (using bootstrap 4 for styling)
<div class="container">
<div class="row">
<?php foreach ($data as $row) : ?>
<div class="col-md-4 col-lg-6">
<img src="<?= base_url($row['photo_path']); ?>" class="img-lazy img-fluid">
</div>
<?php endforeach; ?>
</div>
</div>
Am stuck on what to do next here.
html
<div class="masonry-with-columns-2">
<?foreach ($data as $row){?>
<div>
img here
</div>
<?}?>
</div>
scss
// Within style tags in your html file
body {
margin: 0;
padding: 1rem;
}
// SCSS
// Masonry layout horizontal
.masonry-with-columns-2 {
display: flex;
flex-wrap: wrap;
div {
height: 150px;
line-height: 150px;
background: #9B1B30;
color: white;
margin: 0 1rem 1rem 0;
text-align: center;
font-weight: 900;
font-size: 2rem;
flex: 1 0 auto;
}
#for $i from 1 through 36 {
div:nth-child(#{$i}) {
$h: (random(400) + 70) + px;
width: $h;
}
}
}
Source https://mdbootstrap.com/docs/angular/layout/masonry/

html2pdf PHP generates an additional blank page

I use html2pdf to generate pdf with table data but I have some issue that I can't deal with. No matter how I set margins i always have some additional blank page at the end of pdf.
This is how looks like my pdf template :
<body>
<div class="page">
<div class="inner-page">
<div class="dealers-table">
<div class="head">
<div class="it">Lp.</div>
<div class="name">Name</div>
<div class="street">street</div>
<div class="post-code">Post Code</div>
<div class="city">City</div>
<div class="phone">Phone</div>
<div class="services">Services</div>
</div>
<div class="body">
<div>
<div class="it"></div>
<div class="name"></div>
<div class="street"></div>
<div class="post-code"></div>
<div class="city"></div>
<div class="phone"></div>
<div class="services"> /</div>
</div>
</div>
</div>
</div>
</div>
And css:
.page {
width: 210mm;
height: 280mm;
margin: 0 auto;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
position: relative;
}
.inner-page {
padding: 5mm 10mm;
}
.dealers-table {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
font-size: 6.5pt;
line-height: 1;
}
I don't set any margins in options of my Converter.
When I set page width less than 280px table from second page starts at the end of first page and additional blank page doesn't appear, in other situations there is always useless blank page.
How can I fix it?
EDIT 1
There is some code where I generate pdf on server side:
public function generatePdf() {
$autoDealers = $this->autoDealersOrServices(0);
(some function where i fetch array of dealers from my DB)
$autoDealers = view('pdf.template', [
'autoDealers' => $autoDealers
])->render();
$input = new StringInput();
$input->setHtml($view);
$converter = new Converter($input, new FileOutput());
$converter->setOption('landscape', false);
$converter->setOptions([
'printBackground' => true
]);
$output = $converter->convert();
$output->store('pdf/auto/dealers.pdf');
}
SyntaxEditor Code Snippet
"--encoding UTF-8 --page-size A4 --margin-left 10 --margin-right 10 --margin-top 20 --margin-bottom 0"

Wordpress Woocommerce Product grid equal row height

I'm creating a website using WordPress with Woocommerce plugin. I need to display product page, product title and product short description in product category layout (Grid layout).
My question is product row height not equal. So products are not display as a row in my site. As a solution I would like to divide product grid layout row by row.
Something like that:
http://prnt.sc/ezw0t4
Sample page URL:
http://kitchengallery.lk/all-products/commercial-kitchen-equipments/
Please let me know if you guys have any idea to do this.
Thank You!
SOLUTION 1 : FLEXBOX
Using a flexbox model should do the job. Reference for below code.
Equal height columns - Codepen
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html, body {
height: 100%;
width: 100%;
}
body {
font-family: sans-serif;
line-height: 1.4;
}
h1 {
font-size: 150%;
}
p {
margin-bottom: 10px;
}
.paddingBlock {
padding: 20px 0;
}
.eqWrap {
display: flex;
}
.eq {
padding: 10px;
}
.eq:nth-of-type(odd) {
background: yellow;
}
.eq:nth-of-type(even) {
background: lightblue;
}
.equalHW {
flex: 1;
}
.equalHMWrap {
justify-content: space-between;
}
.equalHM {
width: 32%;
}
.equalHMRWrap {
justify-content: space-between;
flex-wrap: wrap;
}
.equalHMR {
width: 32%;
margin-bottom: 2%;
}
.equalHMVWrap {
flex-wrap: wrap;
}
.equalHMV {
width: 32%;
margin: 1%;
}
.equalHMV:nth-of-type(3n) {
margin-right: 0;
}
.equalHMV:nth-of-type(3n+1) {
margin-left: 0;
}
<div class="paddingBlock">
<h1>EQUAL HEIGHT COLUMNS</h1>
<p>Simply add display:flex to the parent</p>
<div class="equalHWrap eqWrap">
<div class="equalH eq">boo <br> boo</div>
<div class="equalH eq">shoo</div>
<div class="equalH eq">clue</div>
</div>
</div>
<div class="paddingBlock">
<h1>EQUAL HEIGHT + WIDTH COLUMNS</h1>
<p>Add display:flex to the parent and flex:1 to the boxes</p>
<div class="equalHWrap eqWrap">
<div class="equalHW eq">boo <br> boo</div>
<div class="equalHW eq">shoo</div>
<div class="equalHW eq">clue</div>
</div>
</div>
<div class="paddingBlock">
<h1>EQUAL HEIGHT + WIDTH COLUMNS WITH MARGINS</h1>
<p>Add display:flex, justify-content: space-between; to the parent and give a width to the boxes that totals to less than 100%. E.g. These boxes have a width of 32% each. The remaining width of 4% (i.e. 32 x 3 = 96%) will be used to create the space between the boxes and simulate margins. No need to remove margins on the first and last child!</p>
<div class="equalHMWrap eqWrap">
<div class="equalHM eq">boo <br> boo</div>
<div class="equalHM eq">shoo</div>
<div class="equalHM eq">clue</div>
</div>
</div>
<div class="paddingBlock">
<h1>EQUAL HEIGHT COLUMNS WITH MARGINS IN MULTIPLE ROWS</h1>
<p>Building on the above example, just give bottom margins to the boxes. Add a flex-wrap: wrap to the parent, so that boxes go to the next line when they run out of space in a 'row'.</p>
<div class="equalHMRWrap eqWrap">
<div class="equalHMR eq">boo</div>
<div class="equalHMR eq">shoo</div>
<div class="equalHMR eq">clue</div>
<div class="equalHMR eq">boo <br> boo </div>
<div class="equalHMR eq">shoo</div>
<div class="equalHMR eq">clue</div>
</div>
</div>
<div class="paddingBlock">
<h1>EQUAL HEIGHT COLUMNS WITH MARGINS IN MULTIPLE ROWS and VARIABLE NO OF BOXES</h1>
<p>Add display:flex, flex-wrap: wrap to the parent and give a width to the boxes. Give margins to the boxes and remove the left and right margins of the first and last box in each 'row' using the nth-of-type selector. Unlike the previous example, justify-content: space-between on the parent does not work for an uneven number of boxes, because if there are five boxes in all, the third and fifth will align to the left and right of the perceived 'row'.</p>
<div class="equalHMVWrap eqWrap">
<div class="equalHMV eq">boo <br> boo</div>
<div class="equalHMV eq">shoo</div>
<div class="equalHMV eq">clue</div>
<div class="equalHMV eq">boo <br> boo </div>
<div class="equalHMV eq">clue</div>
</div>
</div>
SOLUTION 2: JAVASCRIPT
If browser support is an issue for you then instead of going for flexbox I would recommend that you use JavaScript or jQuery to loop through all the columns in a row, find the column with maximum height in that row and then apply it to all the columns in that row.
Something like this:
function relPostHeight(){
var imgheightArray = [],
headheightArray = [];
$("#related-posts .row .col-sm-3").each(function(){
var imgheight = $(this).find('.featured-image img').height();
var headheight = $(this).find('.entry-header').height();
imgheightArray.push(imgheight);
headheightArray.push(headheight);
});
var minimageHeight = Math.max.apply(Math, imgheightArray);
var minheadHeight = Math.max.apply(Math, headheightArray);
$("#related-posts .featured-image").css({'min-height': minimageHeight});
$("#related-posts .entry-header").css({'min-height': minheadHeight});
}
relPostHeight();
$(window).on('resize', relPostHeight);
Specifically, for woocommerce columns to be all equal in height across the row, we need to convert the old block-style CSS to a flex layout. Here is all the CSS you need to add:
.woocommerce ul.products {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.woocommerce ul.products li.product {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
.woocommerce ul.products li.product a {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
.woocommerce ul.products li.product a:first-child {
-webkit-box-flex: 1;
-ms-flex-positive: 1;
flex-grow: 1;
}
.woocommerce ul.products li.product .button {
margin: 1rem auto;
max-width: 200px;
width: 100%;
}

how to center a div on a page [duplicate]

How can I horizontally center a <div> within another <div> using CSS?
<div id="outer">
<div id="inner">Foo foo</div>
</div>
With flexbox it is very easy to style the div horizontally and vertically centered.
#inner {
border: 0.05em solid black;
}
#outer {
border: 0.05em solid red;
width:100%;
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
To align the div vertically centered, use the property align-items: center.
Other Solutions
You can apply this CSS to the inner <div>:
#inner {
width: 50%;
margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.
If you are targeting Internet Explorer 8 (and later), it might be better to have this instead:
#inner {
display: table;
margin: 0 auto;
}
It will make the inner element center horizontally and it works without setting a specific width.
Working example here:
#inner {
display: table;
margin: 0 auto;
border: 1px solid black;
}
#outer {
border: 1px solid red;
width:100%
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
If you don't want to set a fixed width on the inner div you could do something like this:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
That makes the inner div into an inline element that can be centered with text-align.
The best approaches are with CSS3.
The old box model (deprecated)
display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.
#outer {
width: 100%;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* Safari and Chrome */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* W3C */
display: box;
box-pack: center;
box-align: center;
}
#inner {
width: 50%;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
According to your usability you may also use the box-orient, box-flex, box-direction properties.
The modern box model with Flexbox
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
Read more about centering the child elements
CSS Box Model Module Level 3
Box model (CSS2)
box-align on MDN
And this explains why the box model is the best approach:
Why is the W3C box model considered better?
#centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
<div id="outer" style="width:200px">
<div id="centered">Foo foo</div>
</div>
Make sure the parent element is positioned, i.e., relative, fixed, absolute, or sticky.
If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.
With CSS calc(), the code can get even simpler:
.centered {
width: 200px;
position: absolute;
left: calc(50% - 100px);
}
The principle is still the same; put the item in the middle and compensate for the width.
I've created this example to show how to vertically and horizontally align.
The code is basically this:
#outer {
position: relative;
}
and...
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
And it will stay in the center even when you resize your screen.
Some posters have mentioned the CSS 3 way to center using display:box.
This syntax is outdated and shouldn't be used anymore. [See also this post].
So just for completeness here is the latest way to center in CSS 3 using the Flexible Box Layout Module.
So if you have simple markup like:
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
...and you want to center your items within the box, here's what you need on the parent element (.box):
.box {
display: flex;
flex-wrap: wrap; /* Optional. only if you want the items to wrap */
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
.box {
display: flex;
flex-wrap: wrap;
/* Optional. only if you want the items to wrap */
justify-content: center;
/* For horizontal alignment */
align-items: center;
/* For vertical alignment */
}
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
}
.box {
height: 200px;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
border: 2px solid tomato;
}
.box div {
margin: 0 10px;
width: 100px;
}
.item1 {
height: 50px;
background: pink;
}
.item2 {
background: brown;
height: 100px;
}
.item3 {
height: 150px;
background: orange;
}
<div class="box">
<div class="item1">A</div>
<div class="item2">B</div>
<div class="item3">C</div>
</div>
If you need to support older browsers which use older syntax for flexbox here's a good place to look.
If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.
You can use:
#element {
display: table;
margin: 0 auto;
}
Centering a div of unknown height and width
Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet & Explorer & 10, Opera, etc.)
.content {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>
Tinker with it further on Codepen or on JSBin.
Set the width and set margin-left and margin-right to auto. That's for horizontal only, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment; it's not like you'll break anything.
It cannot be centered if you don't give it a width. Otherwise, it will take, by default, the whole horizontal space.
CSS 3's box-align property
#outer {
width: 100%;
height: 100%;
display: box;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
The way I usually do it is using absolute position:
#inner{
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
position: absolute;
}
The outer div doesn't need any extra properties for this to work.
I recently had to center a "hidden" div (i.e., display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't necessary to display.)
NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and can't be resized/centered until after they are displayed.
$(function(){
$('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
<form action="">
<table id="innerTable">
<tr><td>Name:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="text"></td></tr>
<tr><td>Email:</td><td><input type="submit"></td></tr>
</table>
</form>
</div>
For Firefox and Chrome:
<div style="width:100%;">
<div style="width: 50%; margin: 0px auto;">Text</div>
</div>
For Internet Explorer, Firefox, and Chrome:
<div style="width:100%; text-align:center;">
<div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>
The text-align: property is optional for modern browsers, but it is necessary in Internet Explorer Quirks Mode for legacy browsers support.
Use:
#outerDiv {
width: 500px;
}
#innerDiv {
width: 200px;
margin: 0 auto;
}
<div id="outerDiv">
<div id="innerDiv">Inner Content</div>
</div>
Another solution for this without having to set a width for one of the elements is using the CSS 3 transform attribute.
#outer {
position: relative;
}
#inner {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
The trick is that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.
Here's a Fiddle showing horizontal and vertical alignment.
More information is on Mozilla Developer Network.
Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support than the Flexbox solution, and you're not using display: table; which could break other things.
/* This parent can be any width and height */
.outer {
text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.outer:before {
content: '.';
display: inline-block;
height: 100%;
vertical-align: middle;
width: 0;
overflow: hidden;
}
/* The element to be centered, can
also be of any width and height */
.inner {
display: inline-block;
vertical-align: middle;
width: 300px;
}
I recently found an approach:
#outer {
position: absolute;
left: 50%;
}
#inner {
position: relative;
left: -50%;
}
Both elements must be the same width to function correctly.
For example, see this link and the snippet below:
div#outer {
height: 120px;
background-color: red;
}
div#inner {
width: 50%;
height: 100%;
background-color: green;
margin: 0 auto;
text-align: center; /* For text alignment to center horizontally. */
line-height: 120px; /* For text alignment to center vertically. */
}
<div id="outer" style="width:100%;">
<div id="inner">Foo foo</div>
</div>
If you have a lot of children under a parent, so your CSS content must be like this example on fiddle.
The HTML content look likes this:
<div id="outer" style="width:100%;">
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> Foo Text </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> </div>
<div class="inner"> Foo Text </div>
</div>
Then see this example on fiddle.
Centering only horizontally
In my experience, the best way to center a box horizontally is to apply the following properties:
The container:
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.container {
width: 100%;
height: 120px;
background: #CCC;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="container">
<div class="centered-content">
Center this!
</div>
</div>
See also this Fiddle!
Centering both horizontally & vertically
In my experience, the best way to center a box both vertically and horizontally is to use an additional container and apply the following properties:
The outer container:
should have display: table;
The inner container:
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box:
should have display: inline-block;
Demo:
.outer-container {
display: table;
width: 100%;
height: 120px;
background: #CCC;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
background: #FFF;
padding: 20px;
border: 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
Center this!
</div>
</div>
</div>
See also this Fiddle!
Flexbox
display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.
Please note: Flexbox is compatible all browsers exept Internet Explorer. See display: flex not working on Internet Explorer for a complete and up to date list of browsers compatibility.
#inner {
display: inline-block;
}
#outer {
display: flex;
justify-content: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Text-align: center
Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:
display: block
display: inline
display: inline-block
#inner {
display: inline-block;
}
#outer {
text-align: center;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Margin: 0 auto
Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.
#inner {
display: table;
margin: 0 auto;
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Transform
transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.
#inner {
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
}
<div id="outer">
<div id="inner">Foo foo</div>
</div>
<center> (Deprecated)
The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.
#inner {
display: inline-block;
}
<div id="outer">
<center>
<div id="inner">Foo foo</div>
</center>
</div>
This method also works just fine:
div.container {
display: flex;
justify-content: center; /* For horizontal alignment */
align-items: center; /* For vertical alignment */
}
For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.
The easiest way:
#outer {
width: 100%;
text-align: center;
}
#inner {
margin: auto;
width: 200px;
}
<div id="outer">
<div id="inner">Blabla</div>
</div>
Flex have more than 97% browser support coverage and might be the best way to solve these kind of problems within few lines:
#outer {
display: flex;
justify-content: center;
}
If width of the content is unknown you can use the following method. Suppose we have these two elements:
.outer -- full width
.inner -- no width set (but a max-width could be specified)
Suppose the computed width of the elements are 1000 pixels and 300 pixels respectively. Proceed as follows:
Wrap .inner inside .center-helper
Make .center-helper an inline block; it becomes the same size as .inner making it 300 pixels wide.
Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels wrt. outer.
Set overflow on .outer to hidden to prevent horizontal scrollbar.
Demo:
body {
font: medium sans-serif;
}
.outer {
overflow: hidden;
background-color: papayawhip;
}
.center-helper {
display: inline-block;
position: relative;
left: 50%;
background-color: burlywood;
}
.inner {
display: inline-block;
position: relative;
left: -50%;
background-color: wheat;
}
<div class="outer">
<div class="center-helper">
<div class="inner">
<h1>A div with no defined width</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
Duis condimentum sem non turpis consectetur blandit.<br>
Donec dictum risus id orci ornare tempor.<br>
Proin pharetra augue a lorem elementum molestie.<br>
Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
</div>
</div>
</div>
You can do something like this
#container {
display: table;
width: <width of your container>;
height: <height of your container>;
}
#inner {
width: <width of your center div>;
display: table-cell;
margin: 0 auto;
text-align: center;
vertical-align: middle;
}
This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;
Here is what you want in the shortest way.
JSFIDDLE
#outer {
margin - top: 100 px;
height: 500 px; /* you can set whatever you want */
border: 1 px solid# ccc;
}
#inner {
border: 1 px solid# f00;
position: relative;
top: 50 % ;
transform: translateY(-50 % );
}
You can use display: flex for your outer div and to horizontally center you have to add justify-content: center
#outer{
display: flex;
justify-content: center;
}
or you can visit w3schools - CSS flex Property for more ideas.
Well, I managed to find a solution that maybe will fit all situations, but uses JavaScript:
Here's the structure:
<div class="container">
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
<div class="content">Your content goes here!</div>
</div>
And here's the JavaScript snippet:
$(document).ready(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
If you want to use it in a responsive approach, you can add the following:
$(window).resize(function() {
$('.container .content').each( function() {
container = $(this).closest('.container');
content = $(this);
containerHeight = container.height();
contentHeight = content.height();
margin = (containerHeight - contentHeight) / 2;
content.css('margin-top', margin);
})
});
One option existed that I found:
Everybody says to use:
margin: auto 0;
But there is another option. Set this property for the parent div. It
works perfectly anytime:
text-align: center;
And see, child go center.
And finally CSS for you:
#outer{
text-align: center;
display: block; /* Or inline-block - base on your need */
}
#inner
{
position: relative;
margin: 0 auto; /* It is good to be */
}

using flexbox to get pinterest or jQuery masonry layout

Wanted to know if it is possible to get the same type of design layout as pinterest or jQuery masonry using only the new flexbox layout. Here is as far as I got it:
.flex-container {
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-flow: row wrap;
}
.item {
width: 220px;
height: 250px;
margin: 10px auto;
padding: 0;
background: #ccc;
}
.item:nth-child(3n+2) {
background: #aaa;
height: 400px;
}
and the HTML I am just using a PHP loop to create 12 items
<?php
for ($i=0; $i<=11; $i++) {
echo '<div class="item"></div>';
}
?>
It is entirely possible.
Thanks to #leopld's original answer, I was able to create one that does not depend on a fixed height.
By making the flex container position: absolute or position: fixed, you are able to get it to fill the available space dynamically.
Link to the Codepen: http://codepen.io/anon/pen/Jpnyj?editors=110. I included all the vendor prefixes you'd need at this time.
Markup
<div class="wrapper">
<div class="box box-red"></div>
<div class="box box-blue"></div>
<div class="box box-pink"></div>
<div class="box box-purple"></div>
<div class="box box-green"></div>
<div class="box box-yellow"></div>
<div class="box box-brown"></div>
<div class="box box-red"></div>
<div class="box box-blue"></div>
<div class="box box-pink"></div>
<div class="box box-purple"></div>
<div class="box box-green"></div>
<div class="box box-purple"></div>
<div class="box box-green"></div>
<div class="box box-yellow"></div>
<div class="box box-blue"></div>
<div class="box box-pink"></div>
<div class="box box-purple"></div>
<div class="box box-green"></div>
<div class="box box-yellow"></div>
<div class="box box-red"></div>
<div class="box box-brown"></div>
<div class="box box-blue"></div>
<div class="box box-red"></div>
<div class="box box-green"></div>
<div class="box box-yellow"></div>
<div class="box box-brown"></div>
</div>
Styles
body {
background: black;
}
.wrapper {
position: absolute;
width: 100%;
height: 100%;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-flow: column wrap;
-ms-flex-flow: column wrap;
flex-flow: column wrap;
-webkit-box-align: stretch;
-webkit-align-items: stretch;
-ms-flex-align: stretch;
align-items: stretch;
-webkit-align-content: stretch;
-ms-flex-line-pack: stretch;
align-content: stretch;
}
.box {
margin: 5px;
-webkit-box-flex: 0;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
}
.box-red {
height: 100px;
background: red;
}
.box-blue {
height: 120px;
background: blue;
}
.box-pink {
height: 144px;
background: pink;
}
.box-purple {
height: 250px;
background: purple;
}
.box-green {
height: 200px;
background: green;
}
.box-yellow {
height: 20px;
background: yellow;
}
.box-brown {
height: 290px;
background: brown;
}
CSS3's columns will get you pretty close to that layout. (Note that support in non-recent browsers may be poor, and the spec may change in the future.) The other example didn't work with FF, but this one does:
HTML:
<div id="wrapper">
<div id="cols">
<div class="item">
<img src="http://placekitten.com/400/700?image=1" />
<p>0) Craft beer farm-to-table.</p>
</div>
<div class="item">
<img src="http://placekitten.com/400/450?image=2" />
<p>1) Mollit wolf veniam, leggings art party semiotics Brooklyn High Life sustainable occaecat Banksy actually.</p>
</div>
[more items]
</div>
</div>
CSS:
h1, h2, ul, p { margin: 1rem; }
#wrapper {
width: 900px;
margin: 20px auto;
padding: 10px;
outline: solid black 1px;
background-color: gainsboro;
}
#cols {
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-moz-column-count: 3;
-moz-column-gap: 10px;
column-count: 3;
column-gap: 10px;
}
.item {
display: inline-block;
background: #FEFEFE;
margin: 0;
-webkit-column-break-inside: avoid;
-moz-column-break-inside: avoid;
column-break-inside: avoid;
padding: 10px;
}
.item img {
width: 100%;
border-bottom: 1px solid black;
padding-bottom: 10px;
margin-bottom: 5px;
}
.item p {
font-size:small;
margin: 0;
}
Or play with the full example.
Update: To my knowledge, there is no way of doing this with Flexbox. Flexbox is more concerned with horizontal layout, not vertical. I would be happy to be proven wrong, but that’s what I’ve gathered from my limited experience with it. If you want to learn more, the best article I’ve found on the matter is this: http://css-tricks.com/snippets/css/a-guide-to-flexbox/ (Yes, of course it’s Chris Coyier. How’d you ever guess?)
In any case, even if you can do it with Flexbox it would be a bit of a hack, because that isn’t what Flexbox is for. There’s a much cleaner way of doing it with CSS3 columns. Here’s an example.
Browser support isn't the greatest though: http://caniuse.com/#search=column%20layout Even this example doesn't seem to support Firefox, although I haven't a clue why, since FF does indeed support the respective properties, according to CanIUse.
So, a summary and TLDR: it's an admirable idea, doing this in pure CSS, but for most practical purposes is impossible at the moment. You would probably be better to go with JQuery Masonry
You can actually do it without any greater hassle using flexbox. The only drawback is that you have to specify an absolute height for the wrapper, in order to make the content of it actually wrap. Otherwise it would all be laid out along one great, never ending column.
The HTML:
<div class="wrapper">
<div class="red"></div>
<div class="blue"></div>
<div class="pink"></div>
<div class="purple"></div>
<div class="green"></div>
<div class="yellow"></div>
<div class="brown"></div>
</div>
The (unprefixed) CSS:
.wrapper {
background: black;
display: flex;
flex-flow: column wrap;
height: 450px;
align-items: center;
}
.wrapper > div {
height: 100px;
margin: 5px;
width: 100px;
}
.wrapper > :nth-child(3n+2) {
border: 2px solid white;
height: 300px;
}
I made a JS Fiddle as well, so you can see the result directly.
In a nutshell however, the trick is to use flex-direction: column in combination with flex-wrap: wrap and a fixed height for the wrapper.
I have to add, though - this seems like just the scenario that the CSS columns spec was written for, so KatieK's solution might be a better way to go. Above all, one doesn't need to specify a fixed height for the wrapper when using CSS columns instead of flexbox.

Categories