У меня есть контейнер с фоновым изображением. Я хотел бы это:
- Заполните ширину контейнера постоянно
- если высота контейнера увеличивается, изображение должно прилипать к нижней части и увеличивать зазор в верхней части
- если высота контейнера короче, чем изображение, он должен поддерживать зазор в 20 пикселей вверху, скрывая нижнюю часть изображения (при переполнении)
- Я не знаю высоту / ширину изображения в моем CSS
- Изображение не должно искажаться (соотношение сторон должно сохраняться)
Похоже, мне нужно contain
по ширине, но не по высоте, но тогда я не уверен, как сделать минимальное смещение от вершины.
Смотрите мои попытки здесь:
background-size: 100% auto;
background-position: left 20px;
/* works when the height is shorter than the image
------------------
| |
| |
|................|
|. .|
|. .|
|. .|
|. .bg .|
|. .|
|. .|
|. .|
------------------
. . <- this is clipped off, that is fine.
................
*/
/*
does not work when the height is larger than the image
------------------
| |
| |
|................|
|. .|
|. .|
|. .|
|. .bg .|
|. .|
|. .|
|. .|
|. .|
|. .|
|................| <- I want this to be stuck to the bottom
| |
| |
------------------
*/
background-size: 100% auto;
background-position: left bottom;
/* works when the height is taller than the image
------------------
| |
| |
| |
|................|
|. .|
|. .|
|. .|
|. .bg .|
|. .|
|. .|
|. .|
|. .|
|................| <- stuck to the bottom, good!
------------------
*/
/*
does not work when the height is shorter than the image
................
. .
. .
. .
. .bg .
. . <- This is clipped off
------------------
|. .|
|. .|
|. .|
|................|
------------------
*/
background-size: cover;
background-position: left 20px;
/* works when the width is wider than the image (scales it up)
------------------
| |
| |
|................|
|. .|
|. .|
|. .|
|. .bg .|
|. .|
|. .|
|. .|
------------------
. . <- this is clipped off, that is fine.
................
*/
/*
does not work when the width is narrower than the image, and the height is taller
------------------
| |
| |
|................|.....
|. | . <- I do not want the width to overflow
|. | .
|. | .
|. .bg | .
|. | .
|. | .
|. | .
|. | .
|. | .
|................|.....
------------------
*/
Что я хочу:
/* if the container is shorter than the image
------------------
| |
| |
|................| <- 20px offset from the top, full width of the container
|. .|
|. .|
|. .|
|. .bg .|
|. .|
|. .|
|. .|
------------------
. . <- this is clipped off, that is fine.
................
*/
/*
if the container is larger than the image
------------------
| |
| |
| |
| |
|................| <- full width of the container
|. .|
|. .|
|. .|
|. .bg .|
|. .|
|. .|
|. .|
|. .|
|. .|
|................| <- stuck to the bottom
------------------
*/
Фрагмент для тестирования: