0

Задача: максимально растянуть картинку, под которой расположены кнопки, при этом не должно оставаться пустых областей в родительских блоках (подразумевается что это модальное окно которое закрывается при клике по пустой области (синий блок на картинке - флексбокс должен обтекать картинку и кнопки)). Картинка не должна быть искажена или обрезана, может быть любых размеров, в зависимости от ориентации должна быть максимальна по высоте или ширине.

Единственная проблема которая осталась это выровнять флексбокс по ширине (синяя рамка должна обтекать картинку как на второй схеме).

введите сюда описание изображения

введите сюда описание изображения

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

.Modal {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  /* test */
  border: 3px solid green;
  box-sizing: border-box;
}

.Block {
  max-height: 90vh;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* test */
  border: 3px solid blue;
  box-sizing: border-box;
}

.Block__Image {
  min-height: 0;
  max-height: 100%;
  min-width: 0;
  max-width: 100%;
  /* test */
  border: 3px solid red;
  box-sizing: border-box;
}

.Block__ButtonsWrapper {
  /* test */
  border: 3px solid orange;
  box-sizing: border-box;
}
<html>
  <body>
    <div class="Modal">
      <div tabindex="0">
        <!-- менять можно только здесь -->
        <div class="Block">
          <img class="Block__Image" src="https://get.pxhere.com/photo/tree-branch-plant-sunlight-leaf-flower-green-botany-maple-leaf-translucent-vegetation-deciduous-poplar-outbreak-flowering-plant-grape-leaves-plant-stem-woody-plant-land-plant-609015.jpg" />
          <div class="Block__ButtonsWrapper">
            <button>test</button>
            <button>test</button>
            <button>test</button>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

2
  • Задача: максимально растянуть картинку .Block__Image{width:100%} так? 3 авг 2021 в 12:13
  • @LevShportak задача максимально растянуть по ширине и высоте сохранив пропорции, заранее не известно что больше
    – noctual
    3 авг 2021 в 12:21

1 ответ 1

2

Вариант 1 - максимальное растягивание изображения

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

.Modal {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  /* test */
  border: 3px solid green;
  box-sizing: border-box;
}

.Block {
  max-height: 90vh;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* test */
  border: 3px solid blue;
  box-sizing: border-box;
}

.Block__Image {
  min-height: 0;
  max-height: 100%;
  min-width: 0;
  max-width: 100%;
  width: 100%;         /* ◄◄◄ */
  object-fit: cover;   /* ◄◄◄ */
  /* test */
  border: 3px solid red;
  box-sizing: border-box;
}

.Block__ButtonsWrapper {
  /* test */
  border: 3px solid orange;
  box-sizing: border-box;
}
<html>
  <body>
    <div class="Modal">
      <div tabindex="0">
        <!-- менять можно только здесь -->
        <div class="Block">
          <img class="Block__Image" src="https://get.pxhere.com/photo/tree-branch-plant-sunlight-leaf-flower-green-botany-maple-leaf-translucent-vegetation-deciduous-poplar-outbreak-flowering-plant-grape-leaves-plant-stem-woody-plant-land-plant-609015.jpg" />
          <div class="Block__ButtonsWrapper">
            <button>test</button>
            <button>test</button>
            <button>test</button>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

При маленьком изображении, оно не будет растягиваться - потому что не растягивается родительский элемент <div tabindex="0">.


Вариант 2 - подстройка размеров флексбокса

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

.Modal {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  /* test */
  border: 3px solid green;
  box-sizing: border-box;
}

.Block {
  max-height: 90vh;
  max-width: 90vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* test */
  border: 3px solid blue;
  box-sizing: border-box;
}

.Block__Image {
  min-height: 0;
  max-height: calc(90vh - 27px - 6px);  /* ◄◄◄ */
  min-width: 0;
  max-width: calc(90vw - 6px);          /* ◄◄◄ */
  /* test */
  border: 3px solid red;
  box-sizing: border-box;
}

.Block__ButtonsWrapper {
  /* test */
  border: 3px solid orange;
  box-sizing: border-box;
}
<html>
  <body>
    <div class="Modal">
      <div tabindex="0">
        <!-- менять можно только здесь -->
        <div class="Block">
          <img class="Block__Image" src="https://get.pxhere.com/photo/tree-branch-plant-sunlight-leaf-flower-green-botany-maple-leaf-translucent-vegetation-deciduous-poplar-outbreak-flowering-plant-grape-leaves-plant-stem-woody-plant-land-plant-609015.jpg" />
          <div class="Block__ButtonsWrapper">
            <button>test</button>
            <button>test</button>
            <button>test</button>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

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

16
  • 1
    CSS-свойство object-fit не поддерживается IE (землю - крестьянам, фабрики - рабочим, полифиллы - некрофилам!).
    – yar85
    3 авг 2021 в 12:22
  • Нужно чтобы изображение было полностью видно, с object-fit так же остается пустое пространство
    – noctual
    3 авг 2021 в 12:24
  • 1
    @noctual, чтобы изображение было полностью видно - просто замени object-fit: cover; на height: 100%;, и наслаждайся чудесным искажением. А пустых пространств со значением cover не может оставаться (см. css-справочник, или значение этого англ. слова), если только эти пустоты не являются частью самогó изображения.
    – yar85
    3 авг 2021 в 12:27
  • в том то и дело, изображение не должно быть искажено или обрезано. Уточнил вопрос.
    – noctual
    3 авг 2021 в 12:36
  • @noctual, мы с геометрией не понимаем таких сферических коней которые в любых пропорциях не искажаются и не обрезаются... Просто покажи желаемый результат изображением (сделав его в графическом редакторе в двух вариантах: в альбомной ориентации, и в ландшафтной) - а я покажу как сделать его стилями.
    – yar85
    3 авг 2021 в 12:40

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.