Что такое Flexbox? Описание всех css свойств, основные принципы, преимущества и недостатки. Практическое применение FlexBox Изучаем flexbox и как его применять

Главная / Гаджеты

Why Flexbox?

For a long time, the only reliable cross browser-compatible tools available for creating CSS layouts were things like floats and positioning . These are fine and they work, but in some ways they are also rather limiting and frustrating.

The following simple layout requirements are either difficult or impossible to achieve with such tools, in any kind of convenient, flexible way:

  • Vertically centering a block of content inside its parent.
  • Making all the children of a container take up an equal amount of the available width/height, regardless of how much width/height is available.
  • Making all columns in a multiple column layout adopt the same height even if they contain a different amount of content.

As you"ll see in subsequent sections, flexbox makes a lot of layout tasks much easier. Let"s dig in!

Introducing a simple example

In this article we are going to get you to work through a series of exercises to help you understand how flexbox works. To get started, you should make a local copy of the first starter file - flexbox0.html from our github repo - load it in a modern browser (like Firefox or Chrome), and have a look at the code in your code editor. You can also.

Flex-direction: column;

You"ll see that this puts the items back in a column layout, much like they were before we added any CSS. Before you move on, delete this declaration from your example.

Note : You can also lay out flex items in a reverse direction using the row-reverse and column-reverse values. Experiment with these values too!

Wrapping

One issue that arises when you have a fixed amount of width or height in your layout is that eventually your flexbox children will overflow their container, breaking the layout. Have a look at our flexbox-wrap0.html example, and try viewing it live (take a local copy of this file now if you want to follow along with this example):

Here we see that the children are indeed breaking out of their container. One way in which you can fix this is to add the following declaration to your element represents a standalone section - which doesn" t have a more specific semantic element to represent it contained within an html document.>

rule:

Flex-wrap: wrap; flex: 200px;

Try this now; you"ll see that the layout looks much better with this included:

We now have multiple rows - as many flexbox children are fitted onto each row as makes sense, and any overflow is moved down to the next line. The flex: 200px declaration set on the articles means that each will be at least 200px wide; we"ll discuss this property in more detail later on. You might also notice that the last few children on the last row are each made wider so that the entire row is still filled.

But there"s more we can do here. First of all, try changing your flex-direction property value to row-reverse - now you"ll see that you still have your multiple row layout, but it starts from the opposite corner of the browser window and flows in reverse.

flex-flow shorthand

At this point it is worth noting that a shorthand exists for flex-direction and flex-wrap - flex-flow . So for example, you can replace

Flex-direction: row; flex-wrap: wrap;

Flex-flow: row wrap;

Flexible sizing of flex items

Let"s now return to our first example, and look at how we can control what proportion of space flex items take up. Fire up your local copy of flexbox0.html , or take a copy of flexbox1.html as a new starting point (see it live).

First, add the following rule to the bottom of your CSS:

Article { flex: 1; }

This is a unitless proportion value that dictates how much of the available space along the main axis each flex item will take up. In this case, we are giving each element a value of 1, which means they will all take up an equal amount of the spare space left after things like padding and margin have been set. It is a proportion, meaning that giving each flex item a value of 400000 would have exactly the same effect.

Now add the following rule below the previous one:

Article:nth-of-type(3) { flex: 2; }

Section - article article article - div - button div button div button button button

Let"s look at the code we"ve used for the layout.

Summary

That concludes our tour of the basics of flexbox. We hope you had fun, and will have a good play around with it as you travel forward with your learning. Next we"ll have a look at another important aspect of CSS layouts - CSS Grids.

Дэнни Марков

Дизайн довольно простой - он состоит из выровненного по центру контейнера, внутри которого у нас есть шапка, основной раздел, боковая панель и подвал. Вот главные «испытания», которые мы должны провести, сохраняя CSS и HTML по возможности чистыми:

  1. Разместить четыре основных раздела макета.
  2. Сделать страницу адаптивной (боковая панель опускается ниже основного содержимого на маленьких экранах).
  3. Выровнять содержимое шапки - навигация слева, кнопка справа.

Как вы можете видеть, ради сравнения мы оставили всё максимально простым. Начнём с первого испытания.

Испытание 1. Размещение разделов страницы

Решение на Flexbox

Добавляем display: flex к контейнеру и задаём направление дочерних элементов по вертикали. Это позиционирует все разделы друг под другом.

Container { display: flex; flex-direction: column; }

Теперь нам нужно сделать так, чтобы основной раздел и боковая панель располагались рядом. Поскольку flex-контейнеры обычно однонаправлены, нам нужно добавить дополнительный элемент.

Затем мы устанавливаем этому элементу display: flex и flex-direction с противоположным направлением.

Main-and-sidebar-wrapper { display: flex; flex-direction: row; }

Последний шаг - задать размеры основного раздела и боковой панели. Мы хотим, чтобы основное содержимое было в три раза шире боковой панели, что несложно сделать с помощью flex или процентов.

Как вы можете видеть, Flexbox сделал всё хорошо, но нам кроме этого понадобилось довольно много свойств CSS плюс дополнительный элемент HTML. Давайте посмотрим, как будет работать CSS Grid.

Решение на CSS Grid

Существует несколько вариантов использования CSS Grid, но мы воспользуемся синтаксисом grid-template-areas , как наиболее подходящего для наших целей.

Сперва мы определим четыре grid-area , по одному на каждый раздел страницы:

header { grid-area: header; } .main { grid-area: main; } .sidebar { grid-area: sidebar; } footer { grid-area: footer; }

Теперь мы можем настроить нашу сетку и определить расположение каждой области. Вначале код может показаться довольно сложным, но как только вы познакомитесь с системой сетки, он становится проще для понимания.

Container { display: grid; /* Определяем размер и число колонок нашей сетки. Единица fr работает подобно Flexbox: колонки делят свободное пространство в строке согласно их значениям. У нас будет две колонки - первая в три раза больше второй. */ grid-template-columns: 3fr 1fr; /* Связываем сделанные ранее области с местами в сетке. Первая строка - шапка. Вторая строка делится между основным разделом и боковой панелью. Последняя строка - подвал. */ grid-template-areas: "header header" "main sidebar" "footer footer"; /* Интервал между ячейками сетки будет 60 пикселей */ grid-gap: 60px; }

Вот и всё! Наш макет теперь будет соответствовать указанной выше структуре и мы его настроили так, что нам не придётся иметь дело с margin или padding .

Испытание 2. Делаем страницу адаптивной

Решение на Flexbox

Выполнение этого шага строго связано с предыдущим. Для решения на Flexbox нам придётся изменить flex-direction и отрегулировать margin .

@media (max-width: 600px) { .main-and-sidebar-wrapper { flex-direction: column; } .main { margin-right: 0; margin-bottom: 60px; } }

Наша страница довольно простая, поэтому в медиа-запросе мало работы, но в более сложном макете придётся много чего переделывать.

Решение на CSS Grid

Поскольку мы уже определили grid-areas , нам просто нужно переопределить их порядок в медиа-запросе. Мы можем использовать ту же настройку колонок.

@media (max-width: 600px) { .container { /* Выравнивание областей сетки для мобильного макета */ grid-template-areas: "header header" "main main" "sidebar sidebar" "footer footer"; } }

Или можем переопределить весь макет с нуля, если считаем, что это решение чище.

@media (max-width: 600px) { .container { /* Переделываем сетку в одноколоночный макет */ grid-template-columns: 1fr; grid-template-areas: "header" "main" "sidebar" "footer"; } }

Испытание 3. Выравнивание компонентов шапки

Решение на Flexbox

Мы уже делали похожий макет на Flexbox в одной из наших старых статей - . Техника довольно простая:

Header { display: flex; justify-content: space-between; }

Теперь список навигации и кнопка выровнены правильно. Осталось только разместить пункты внутри

© 2024 mchard.ru -- Ноутбук. Работа с текстом. Монитор. Гаджеты. Компьютер. Skype. Восстановление