Центрирование чувствительных элементов в контейнере горизонтальной прокрутки - PullRequest
0 голосов
/ 27 января 2020

Я создал контейнер (красная граница с линией, обозначающей центр), которая прокручивается по горизонтали при переполнении.

Первый дочерний элемент (фиолетовый блок) этого контейнера всегда является кнопкой.

enter image description here

При нажатии этой кнопки в контейнер добавляются дополнительные дочерние элементы.

enter image description here

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

У меня возникают трудности с выяснением этого, потому что я применил min-width (т.е. 100px) в дополнение к отзывчивому width (т.е. 25vw) к дочерним элементам.

Первоначально я планировал добиться этого путем применения padding-left к родительскому контейнеру, а затем псевдоэлемента ::after к :not(.first-child).children:last-child, но затем Я понял, что подход не достаточно Если я хочу, чтобы он был полностью отзывчивым. Тем не менее, я знаю, что могу вручную вычислить, при какой ширине будет запускаться min-width, а затем использовать запрос @media, но я надеюсь, что есть лучший способ.

#container {
  width: 100%;
  height: 100%;
  padding-left: ; /* Half the window width minus half the width of the child. */
  overflow-x: scroll;
  display: flex;
  align-items: center;
  background: skyblue;
  box-sizing: border-box;
  border: solid red 2px;
}

#container::-webkit-scrollbar {
  display: none;
}

.children {
  width: 25vw;
  min-width: 100px;
  height: 50%;
  min-height: 200px;
  position: relative;
  margin-right: 5%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: purple;
}

:not(.first-child).children:last-child::after {
  content: '';
  width: ; /* Half the window width minus half the width of the child. */
  height: 100%;
  position: relative; /* relative or absolute      */
  left: ;             /* and offset appropriately. */
  transform: ;        /*                           */
}

Есть ли у кого-нибудь идеи? как это сделать?

Ответы [ 2 ]

2 голосов
/ 27 января 2020

Вы можете применить margin-left к первому дочернему элементу, а для обработки минимальной ширины вы можете использовать медиа-запрос. Когда экран меньше 400px, 25vw будет меньше 100px, и вы изменяете значение для рассмотрения 100px.

#container {
  position: fixed;
  top:0;
  left:0;
  width: 100%;
  height: 100%;
  overflow-x: scroll;
  display: flex;
  align-items: center;
  background: 
    linear-gradient(red,red) center/1px 100% no-repeat,
    skyblue;
  box-sizing: border-box;
  border: solid red 2px;
}

#container::-webkit-scrollbar {
  display: none;
}

.children {
  width: 25vw;
  min-width: 100px;
  height: 40%;
  min-height: 100px;
  position: relative;
  margin-right: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: purple;
  flex-shrink:0; /* don't forget this to avoid the shrink */
}

.children:first-child {
  margin-left: calc(50% - 12.5vw);
}

@media (max-width:400px) {
  .children:first-child {
    width: 25vw;
    min-width: 100px;
    margin-left: calc(50% - 50px);
  }
}
<div id="container">
  <div class="children"></div>
  <div class="children"></div>
  <div class="children"></div>
  <div class="children"></div>
</div>

Без медиазапроса вы можете рассмотреть псевдоэлемент, где у вас будет ограничение max-width:

#container {
  position: fixed;
  top:0;
  left:0;
  width: 100%;
  height: 100%;
  overflow-x: scroll;
  display: flex;
  align-items: center;
  background: 
    linear-gradient(red,red) center/1px 100% no-repeat,
    skyblue;
  box-sizing: border-box;
  border: solid red 2px;
}

#container::-webkit-scrollbar {
  display: none;
}

.children {
  width: 25vw;
  min-width: 100px;
  height: 40%;
  min-height: 100px;
  position: relative;
  margin-right: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: purple;
  flex-shrink:0;
}

#container:before { 
  content:"";
  width: calc(50% - 12.5vw);
  max-width:calc(50% - 50px);
  flex-shrink:0;
}
<div id="container">
  <div class="children"></div>
  <div class="children"></div>
  <div class="children"></div>
  <div class="children"></div>
</div>
0 голосов
/ 28 января 2020

Мне удалось создать строго адаптивное решение, используя calc, хотя я использую vh в качестве width детей. CSS - спаситель.

#container {
--offset: calc(50vw - ((100vh / 100) * 20);
  padding-left: var(--offset);
  background: skyblue;
}

.children {
  min-width: 40vh; /* vh is used for width to account for the height of window. */
  min-height: 60vh;
  position: relative;
  background: purple;
}

:not(.first-child).children:last-child::after {
  content: '';
  width: var(--offset);
  height: 1px;
  position: absolute;
  left: 100%;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...