Css grid reverse row

Обратный порядок столбцов в CSS Grid Layout

Я надеялся использовать CSS Grid, чтобы отменить видимый порядок двух бок о бок div, где один из divs растет произвольно (я не хочу использовать float). Я создал plunkr здесь: http://plnkr.co/edit/6WZBnHbwhD7Sjx2ovCO7?p=preview

#container < grid-template-columns: 240px 1fr; display: grid; >.a < background: yellow; >.b < background: blue; color: white; >#container>.a < grid-column: 1; >#container>.b < grid-column: 2; >#container.reverse>.a < grid-column: 2; >#container.reverse>.b

Суть его в том, что когда я применяю класс .reverse (так что вы должны видеть B | A ), B смещается к новой строке, поэтому выглядит больше:

Если я инвертирую порядок документов .a с помощью .b , это вернется к нормальному (но, конечно, если я опустил класс .reverse , я получаю ту же проблему). Почему это и как я могу обратиться?

2 ответа

Поскольку алгоритм автоматического размещения сетки содержит элементы в контейнере, он использует следующие доступные пустые ячейки (source). В исходном коде элемент A находится перед элементом B:

Поэтому контейнер сетки сначала помещает A, а затем использует следующее доступное пространство для размещения B.

По умолчанию алгоритм автоматического размещения выглядит линейно через сетку без обратного слежения; если он должен пропустить некоторые пустые места, чтобы разместить более крупный элемент, он не вернется, чтобы заполнить эти пробелы. Чтобы изменить это поведение, укажите ключевое слово dense в grid-auto-flow . http://www.w3.org/TR/css3-grid-layout/#common-uses-auto-placement

grid-auto-flow: dense

Одним из решений этой проблемы (как вы отметили) является переопределение значения по умолчанию grid-auto-flow: row с помощью grid-auto-flow: dense . С помощью grid-auto-flow: dense алгоритм автоматического размещения сетки будет искать обратные заполненные незанятые ячейки элементами, которые соответствуют.

7.7. Автоматическое размещение: grid-auto-flow Свойство Элементы сетки, которые явно помещены, автоматически помещаются в незанятое пространство в контейнере сетки путем автоматического размещения алгоритм. grid-auto-flow управляет тем, как работает алгоритм автоматического размещения, точно указывая, как автоматически помещенные элементы попадают в сетку. dense Если указано, алгоритм автоматического размещения использует «плотную» упаковку алгоритм, который пытается заполнить дыры ранее в сетке, если позже появятся более мелкие предметы. Это может привести к появлению элементов вне очереди, когда это будет заполнять отверстия, оставленные более крупными предметами.

#container < display: grid; grid-template-columns: 240px 1fr; grid-auto-flow: dense; /* NEW */ >.a < background: yellow; >.b < background: blue; color: white; >#container>.a < grid-column: 1; >#container>.b < grid-column: 2; >#container.reverse>.a < grid-column: 2; >#container.reverse>.b

grid-row: 1

Источник

Reverse order of columns in CSS Grid Layout

As the Grid auto-placement algorithm lays out items in the container, it uses next available empty cells (source).

In your source code the A element comes before the B element:

Therefore, the grid container first places A, then uses the next available space to place B.

By default, the auto-placement algorithm looks linearly through the grid without backtracking; if it has to skip some empty spaces to place a larger item, it will not return to fill those spaces. To change this behavior, specify the dense keyword in grid-auto-flow .

http://www.w3.org/TR/css3-grid-layout/#common-uses-auto-placement

grid-auto-flow: dense

One solution to this problem (as you have noted) is to override the default grid-auto-flow: row with grid-auto-flow: dense .

With grid-auto-flow: dense , the Grid auto-placement algorithm will look to back-fill unoccupied cells with items that fit.

7.7. Automatic Placement: the grid-auto-flow property

Grid items that aren’t explicitly placed are automatically placed into an unoccupied space in the grid container by the auto-placement algorithm.

grid-auto-flow controls how the auto-placement algorithm works, specifying exactly how auto-placed items get flowed into the grid.

dense

If specified, the auto-placement algorithm uses a “dense” packing algorithm, which attempts to fill in holes earlier in the grid if smaller items come up later. This may cause items to appear out-of-order, when doing so would fill in holes left by larger items.

#container < display: grid; grid-template-columns: 240px 1fr; grid-auto-flow: dense; /* NEW */ >.a < background: yellow; >.b < background: blue; color: white; >#container>.a < grid-column: 1; >#container>.b < grid-column: 2; >#container.reverse>.a < grid-column: 2; >#container.reverse>.b

grid-row: 1

Another solution would be to simply define the row for the second item.

#container < display: grid; grid-template-columns: 240px 1fr; >.a < background: yellow; >.b < background: blue; color: white; >#container>.a < grid-column: 1; >#container>.b < grid-column: 2; grid-row: 1; /* NEW */ >#container.reverse>.a < grid-column: 2; >#container.reverse>.b

The simplest way is to add order: 1 to element B or order: -1 to element A in .reverse

It’s also correct CSS rather than hack-y

Источник

How to reverse the css grid columns order?

(without some manual definition, because I do not know how many lines will be in advance) Solution 1: If you don’t mind setting as many css rules as the maximum expected number of rows, this trick can work for you: Use a content query to force some elements, based in the total number of elements, to go to a specific row References for quantity queries: a list apart css tricks online tool Solution 2: Another option might be to use column-count rather than grid: demo: https://codepen.io/RuaScribe/pen/PoYEaEw info: Question: After getting to grips with flexbox, I’ve started learning CSS grid.

How to reverse the css grid columns order?

I want to be able to reverse the order of columns (the 2 small to the left, the big one right). I’ve tried several solutions but didn’t find one that works.

.images-block-box < display: grid; grid-gap: 16px; grid-template-columns: 708fr 340fr; & >div:first-child < grid-row: span 2; >&.reverse < grid-template-columns: 340fr 708fr; & >div:first-child < order: 2; // doesn't work (I want to place the first item at the end of the 3) >>// reverse >// images-block-box 

Note that I really want to reverse the order of the columns themselves, not just their dimensions.

Simply adjust grid-column and conisder grid-auto-flow:dense; to allow the next elements to be placed before:

.grid < display: grid; grid-gap: 16px; grid-template-columns: 2fr 1fr; grid-auto-flow:dense; margin:5px; >.grid div < min-height: 50px; border: 1px solid; >.grid div:first-child < grid-row: span 2; >.grid.reverse < grid-template-columns: 1fr 2fr; >.grid.reverse div:first-child

dense

If specified, the auto-placement algorithm uses a “dense” packing algorithm, which attempts to fill in holes earlier in the grid if smaller items come up later . This may cause items to appear out-of-order, when doing so would fill in holes left by larger items. ref

Another option is to place the big box to the last column by using grid-column-end: -1 — see demo below:

.images-block-box < display: grid; grid-gap: 16px; grid-template-columns: 708fr 340fr; grid-template-rows: 100px 100px; grid-auto-flow: column; >.images-block-box>div < border: 1px solid; >.images-block-box>div:first-child < grid-row: span 2; >.images-block-box.reverse < grid-template-columns: 340fr 708fr; >.images-block-box.reverse>div:first-child

grid-column-end

&& ?

Contributes the nth grid line to the grid item’s placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid.

Since there are 2 answers that could be marked as accepted (thanks to @kukkuz and @Temani Afif) I’m posting here a sum up. The working techniques pointed out till now are:

  • grid-auto-flow: dense (container) + grid-column: 2 (first-child)
  • grid-auto-flow: column (container) + grid-column-end: -1 (first-child)

The rest of the code remains the same. Please take a look at the related answers.

Both are currently working well (at least in major/modern browsers).

Then Maybe You can use a different approach

.grid < display: grid; grid-template-columns: 5fr 2fr; grid-template-rows: 1fr 1fr; height: 500px; grid-gap: 2rem; >.one < background-color: red; grid-row: 1 / 3; >.two < background-color: green; >.three < background-color: blue; >.reverse > .one < grid-column: 2 / 3; grid-row: 2 / 3; >.reverse > .three < grid-column: 1 / 2; grid-row: 1 / 3; >

Css — How can I reverse the order of columns in, In CSS Flexbox, why are there no «justify-items» and «justify-self» properties? Hot Network Questions Name for motivation for synchronic reduction phenomena such as elision or fusion

CSS grid — reverse order column/rows, its possible? [duplicate]

im playing with css 3 grid and i have one question. I created demo:

My question: is possible to get with some grid value or some trick example below? (without some manual definition, because I do not know how many lines will be in advance)

If you don’t mind setting as many css rules as the maximum expected number of rows, this trick can work for you:

Use a content query to force some elements, based in the total number of elements, to go to a specific row

var numElements = 4;function add ()
ul < border: 3px solid goldenrod; display: grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 50px; margin: 0; padding: 0; grid-gap: 10px; width: 300px; grid-auto-flow: column; >li < background: pink; margin: 0; padding: 0; list-style: none; text-align: center; line-height: 50px; >li:nth-child(2):nth-last-child(n + 3) < grid-row: 2; background: tomato; >li:nth-child(3):nth-last-child(n + 5) < grid-row: 3; background: tomato; >li:nth-child(4):nth-last-child(n + 7) < grid-row: 4; background: tomato; >li:nth-child(5):nth-last-child(n + 9) < grid-row: 5; background: tomato; >li:nth-child(6):nth-last-child(n + 11) < grid-row: 6; background: tomato; >li:nth-child(7):nth-last-child(n + 13) < grid-row: 7; background: tomato; >li:nth-child(8):nth-last-child(n + 15) < grid-row: 8; background: tomato; >li:nth-child(4):nth-last-child(1)

References for quantity queries:

Another option might be to use column-count rather than grid:

This sounds like a great use for grid-auto -flow.

Html — Achieving flexbox row-reverse in css grid, 2 Answers. You have 2 elements so simply change the order of one element. Tell the image and text in every second grid container to switch sides. .grid:nth-child (2n + 2) > div:first-child < grid-column: 2; >You also need to specify grid-auto-flow: dense on the grid container, or grid-row: 1 on the items, so the …

Achieving flexbox row-reverse in css grid

After getting to grips with flexbox, I’ve started learning CSS grid .

Here’s a simple flexbox grid that I’ve built before:

.container < width: 500px; max-width: 100%; margin: 0 auto; >.flex < display: flex; flex-flow: row wrap; >.col < padding: 24px; flex: 1; >.flex:nth-child(even) < flex-flow: row-reverse wrap; text-align: left; >img
I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

As you can see, the image alternates using flex-flow: row-reverse wrap; .

My question: Is it possible to do the same thing using CSS grid? How would I achieve this?

Here’s how it’s looking in CSS grid so far. Any ideas?

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

You have 2 elements so simply change the order of one element.

.container < width: 500px; max-width: 100%; margin: 0 auto; >.grid < display: grid; grid-template-columns: repeat(2, 1fr);>.col < padding: 24px; >img < height: auto; max-width: 100%; >.grid:nth-child(even) .col:last-child
I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

You can also do the same with flexbox:

.container < width: 500px; max-width: 100%; margin: 0 auto; >.grid < display: flex; flex-flow: row wrap; >.col < padding: 24px; flex: 1; >img < height: auto; max-width: 100%; >.grid:nth-child(even) .col:last-child
I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

Tell the image and text in every second grid container to switch sides.

.grid:nth-child(2n + 2) > div:first-child

You also need to specify grid-auto-flow: dense on the grid container, or grid-row: 1 on the items, so the items render on the same row.

.grid < display: grid; grid-template-columns: repeat(2, 1fr); grid-auto-flow: dense; /* tells grid to fill open space earlier in the grid */ >.grid:nth-child(2n + 2)>div:first-child < grid-column: 2; >.col < padding: 24px; >img < height: auto; max-width: 100%; >.container
I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

I'm A Title

Here's some copy.

Grid-column-end — CSS: Cascading Style Sheets, If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. If a name is given as a , only lines with that name are counted. If not enough lines with that name exist, all implicit grid lines are assumed to have that name for the purpose of finding this position.

Источник

Читайте также:  Последнее число фибоначчи питон
Оцените статью