Как масштабировать изображение, чтобы вписаться в гибкую коробку в сеткуCSS

Разбираемся в CSS
Ответить Пред. темаСлед. тема
Anonymous
 Как масштабировать изображение, чтобы вписаться в гибкую коробку в сетку

Сообщение Anonymous »

Я хочу создать страницу «приборной панели», которая использует все доступное пространство в окне браузера. Окно браузера будет разделено на две стороны равной ширины. Правая боковая пространство будет содержать слайд -шоу. Изображения, которые больше, чем доступное пространство, должны быть увеличены, чтобы соответствовать и быть центрированными в пространстве. Тело содержит двухколонную сетку, размеры которых составляют 1FR & 1FR. Righthand Griditem -это Flexbox. Это, в свою очередь, содержит Flexbox , содержащий .
Обязательно нажмите «Полностраничная» ссылка для фрагмента и увеличить окно браузера, если это необходимо.
Я не могу понять, что мне нужно сделать, чтобы позволить Expland rize prese> expdand of-pree> expdand of-prese> expdand of-p-p-right-prese>. Изображение правильно сжимается как по высоте, так и по ширине, чтобы соответствовать, когда размеры окна изображения указываются в абсолютных единицах. < /P>

Код: Выделить всё

/* Slideshow generates rectangles of various dimensions */
const duration = 1500; // time (msec) to display each slide
const sleep = ms => new Promise(r => setTimeout(r, ms));
const sizes = [
[4000, 500, "Oversize horizontal"],
[1000, 4000, "Oversize vertical"],
[400, 300, "Should fit"],
[100, 200, "Very small"],
[4000, 4000, "Oversize square"]
];

async function show_slide_test(duration, min = 0, max = 0) {
let n = 0;
const my_img = document.querySelector('#slide-div-img');
let my_randomizer;
while (true) {
let size_index = n++ % sizes.length;
let w = sizes[size_index][0];
let h = sizes[size_index][1];
let desc = sizes[size_index][2];
let my_randomizer = `https://placehold.co/${w}x${h}/orange/black/png?text=${desc}\\n${w}+x+${h}+px`;
try {
const my_response = await fetch(my_randomizer);
const my_blob = await my_response.blob();
URL.revokeObjectURL(my_img.src);
const my_url = URL.createObjectURL(my_blob);
my_img.src = my_url;
await sleep(duration);
} catch (my_error) {
console.error('Error: ', my_error);
break;
}
}
}< /code>
* {
box-sizing: border-box;
}

html {
height: 100%;
width: 100%;
}

body {
outline: 4px dashed red;
outline-offset: -4px;
height: 100%;
/* limit to height of html */
width: 100%;
margin: 0;
/* prevent body from shifting */
padding: 0;
overflow: hidden;
/* prevents any body scroll */
}

/* Divide body into a grid of 2 columns */
panels {
background: blue;
min-height: 100%;
display: grid;
grid-template-columns: 50fr 50fr;
gap: 2em;
}

/* Left-hand panel */
left-panel {
background: pink;
}

/* Right-hand panel */
right-panel {
background: yellow;
display: flex;
justify-content: center;
align-items: center;
}

/* Flex item inside right panel flexbox */
picture-box {
background: green;
display: flex;
justify-content: center;
align-items: center;
/* what magic values will make picture box grow to size of right-panel? */
width: 600px;
height: 400px;
}

.scaled-picture {
outline: 8px double black;
outline-offset: -8px;
max-width: 100%;
max-height: 100%;
}< /code>





















Обновление , чтобы представить MRE в своих вопросах, я попытался разбить свои проблемы с панелью на два меньших вопроса. Более ранние проблемы левой панели были решены здесь, и я наивно предположил, что этот вопрос, касающийся слайд -шоу на правой панели, может быть решен независимо, а затем добавлен к другому. Не так. Поэтому мне придется предоставить еще один фрагмент, который включает в себя детали левой панели. Вместо этого он просто размещает ширину, позволяя высоким изображениям расширяться вертикально ниже нижнего края панели. Я не знаю, какой из двух подходов, используемых в ответах, «лучше»; Они оба работают для моего оригинального MRE, но не в более широком контексте моей панели приборной панели.

Код: Выделить всё

/* This function populates the scrollable-container grid with variable
numbers of rows of dummy data */
let my_limit;
const my_perday = 3;

function load_scrollable_table(limit) {
my_limit = limit;
if (my_limit < 1) {
return;
}
const my_div = document.querySelector("#whatsnew");
for (let day = 1;; day++) {
if (!insert_row(my_div, `3/${day}/2025`, 'Foobar etc.')) {
return;
}
for (let thisday = 1; thisday < my_perday; ++thisday) {
let v = "foo ".repeat(thisday * 4);
if (!insert_row(my_div, '', 'Foobar more etc.' + v)) {
return;
}
}
}
}

function insert_row(my_div, col1, col2) {
let my_row = `${col1}
${col2}`;
my_div.innerHTML += my_row;
return --my_limit;
}

/*
* Slideshow_test generates a sequence of five images that are
* inserted into the right panel, scaled proportionally to fit
* the available space.
*
* - 4000x500px exceeds the width of the container
* - 1000x4000px exceeds the height of the container
* - 4000x4000px exceeds both the width and the height of the container.
* - 600x400px should fit within the container without any scaling
* - 100x200px should also fit.  It's included to prove that it isn't scaled up.
*/
const duration = 2000; // time (msec) to display each slide
const min_size = 0; // min file size to select
const max_size = 0; // max file size (0 means no limit)
const sleep = ms => new Promise(r => setTimeout(r, ms));
const sizes = [
/* wd, ht */
[4000, 500],
[1000, 4000],
[4000, 4000],
[600, 400],
[100, 200]
];

async function slideshow_test(duration, min = 0, max = 0) {
let n = 0;

const my_img = document.querySelector('#slide-img');
let my_randomizer;
while (true) {
let size_index = n++ % sizes.length;
let w = sizes[size_index][0];
let h = sizes[size_index][1];

let my_randomizer = `https://placehold.co/${w}x${h}/orange/black/png?text=Pre-scaled+size\\n${w}+x+${h}+px`;
try {
const my_response = await fetch(my_randomizer);
const my_blob = await my_response.blob();
URL.revokeObjectURL(my_img.src);
const my_url = URL.createObjectURL(my_blob);
my_img.src = my_url;
await sleep(duration);
} catch (my_error) {
console.error('Error: ', my_error);
break;
}
}
}< /code>
:root {
/*
* I don't know of any way to give  the margins I want without
* somehow destroying the "dashboard" appearance, so I set variables
* here and use them in several places to fake it.
*/
--body-margin-sides: 2em;
--body-margin-top: 2em;
--body-margin-bottom: 2em;
--body-background: #dbd2c3;
}

* {
box-sizing: border-box;
}

html,
body {
height: 100%;
}

html {
background: violet;
}

/* BODY and LEFT PANEL are taken from Brett Donald's solution,
https://stackoverflow.com/a/79453218/522385 */
body {
outline: 4px dashed red;
outline-offset: -4px;
background: var(--body-background);
margin: 0 var(--body-margin-sides);
/* side margins only */
display: grid;
overflow: hidden;
/* prevents any body scroll -- good for dashboards */
/* height: 100%; */
/* width: 100% */
/* padding: 0;  */
grid-template-rows: var(--body-margin-top)
/* fake top margin */
auto
/* header */
1fr
/* widget area */
var(--body-margin-bottom);
/* fake bottom margin */
}

fake-body-margin {
background: violet;
}

header {
background: lightgreen;
text-align: center;
}

hr {
display: block;
margin: var(--body-margin-top) auto;
width: 100%;
border: 0;
border-top: 1px dashed black;
}

panels {
display: grid;
gap: 5em;
grid-template-columns: 45fr 55fr;
}

left-panel {
outline: 3px dotted green;
outline-offset: -3px;
display: grid;
grid-template-rows: auto 1fr;
}

left-panel-top {
margin-top: 15px;
/* Gap above Welcome blurb */
line-height: 1.4;
/* line separation is 1.4 x normal */
margin-bottom: 0px;
/* Gap beneath Welcome blurb */
}

left-panel-bottom {
position: relative;
}

left-panel-bottom-content {
background: orange;
border: 0;
border-radius: 5px;
/* border roundedness */
column-gap: 10px;
display: grid;
grid-template-columns: auto auto;
max-height: 100%;
overflow: auto;
/* scroll the overflow */
padding: 0 1em;
position: absolute;
/* prevents content height from affecting the layout*/
width: fit-content;
/* I changed from 100% */
}

/* Hide scrollbar for Webkit browsers */
left-panel-bottom-content::-webkit-scrollbar {
display: none;
}

/* Hide scrollbar for IE, Edge and Firefox */
left-panel-bottom-content {
-ms-overflow-style: none;
/* IE and Edge */
scrollbar-width: none;
/* Firefox */
}

scrollable-table-col1 {
height: fit-content;
}

scrollable-table-col2 {
height: fit-content;
}

scrollable-table-spacer {
padding-bottom: 6px;
}

/* RIGHT-PANEL is taken from imh's solution */
right-panel {
outline: 4px dotted black;
outline-offset: -4px;
background: yellow;
display: flex;
flex-direction: column;
/* this appears to have no effect */
overflow: hidden;
}

picture-box {
outline: 4px dotted orange;
outline-offset: -4px;
display: flex;
flex: auto;
min-height: 0;
justify-content: center;
/* Centers horizontally */
align-items: center;
/* Centers vertically */
}

.scaled-picture {
outline: 8px double black;
outline-offset: -8px;
max-width: 100%;
/* leave a little breathing room */
max-height: 100%;
}< /code>



Banner






Lorem ipsum odor amet, consectetuer adipiscing elit. Maecenas tempor
proin amet ad consequat tempor praesent facilisis. Tempus potenti
torquent nulla nullam elit class malesuada. Ut platea id ornare,
convallis fusce eros. Fringilla pretium porta phasellus consectetur
fermentum semper mollis. Est imperdiet euismod placerat et venenatis
mattis; magna dictumst integer. Turpis fusce malesuada venenatis diam
nisl quis tempus nostra. In nulla mollis ac nisi turpis consequat arcu
potenti? Inceptos congue potenti at montes erat ac ultricies vel
maximus.  Ridiculus nunc porttitor tortor vulputate; posuere quisque.

Recent site updates:















 







Обновление 2: я хотел посмотреть, смогу ли я добавить второй прокрученный список в , справа от первого. Я превратил в сетку с двумя столбцами равной ширины. В HTML я добавил второй . Но так как определяется как позиция: Absolute , две элементы сетки были наложены. И, конечно же, позиция: Absolute необходимо для того, чтобы элементы оставались в своих контейнерах, как я хочу. < /P>
-это то, что нужно каким-то элементом сетки, скажем, < /code>, чтобы сесть в левый панель-панель и содержать две коробки содержимого? class = "Snippet-Code">

Код: Выделить всё

/* This function populates the scrollable-container grid with variable
numbers of rows of dummy data */
let my_limit;
const my_perday = 3;

function load_scrollable_table(limit, id) {
my_limit = limit;
if (my_limit < 1) {
return;
}
const my_div = document.querySelector(`#${id}`);
for (let day = 1;; day++) {
if (!insert_row(my_div, `3/${day}/2025`, `${id} etc.`)) {
return;
}
for (let thisday = 1; thisday < my_perday; ++thisday) {
let v = "foo ".repeat(thisday * 4);
if (!insert_row(my_div, '', `${id} more etc.` + v)) {
return;
}
}
}
}

function insert_row(my_div, col1, col2) {
let my_row =
`${col1}`
+ `${col2}`;
my_div.innerHTML += my_row;
return --my_limit;
}

/*
* Slideshow_test generates a sequence of five images that are
* inserted into the right panel, scaled proportionally to fit
* the available space.
*
* - 4000x500px exceeds the width of the container
* - 1000x4000px exceeds the height of the container
* - 4000x4000px exceeds both the width and the height of the container.
* - 600x400px should fit within the container without any scaling
* - 100x200px should also fit.  It's included to prove that it isn't scaled up.
*/
const duration = 2000; // time (msec) to display each slide
const min_size = 0; // min file size to select
const max_size = 0; // max file size (0 means no limit)
const sleep = ms => new Promise(r => setTimeout(r, ms));
const sizes = [
/* wd, ht */
[4000, 500],
[1000, 4000],
[4000, 4000],
[600, 400],
[100, 200]
];

async function slideshow_test(duration, min = 0, max = 0) {
let n = 0;

const my_img = document.querySelector('#slide-img');
let my_randomizer;
while (true) {
let size_index = n++ % sizes.length;
let w = sizes[size_index][0];
let h = sizes[size_index][1];

let my_randomizer = `https://placehold.co/${w}x${h}/orange/black/png?`
+ `text=Pre-scaled+size\\n${w}+x+${h}+px`;
try {
const my_response = await fetch(my_randomizer);
const my_blob = await my_response.blob();
URL.revokeObjectURL(my_img.src);
const my_url = URL.createObjectURL(my_blob);
my_img.src = my_url;
await sleep(duration);
} catch (my_error) {
console.error('Error: ', my_error);
break;
}
}
}< /code>
:root {
--body-margin-sides: 2em;
--body-margin-top: 2em;
--body-margin-bottom: 2em;
--body-margin-color: violet;
--body-background: #dbd2c3;
--body-fontsize: 80%;
}

* {
box-sizing: border-box;
}

html,
body {
height: 100%;
}

html {
background: var(--body-margin-color);
}

/* BODY and LEFT PANEL are taken from Brett Donald's solution,
https://stackoverflow.com/a/79453218/522385 */
body {
outline: 4px dashed red;
outline-offset: -4px;
background: var(--body-background);
/* side margins only */
margin: 0 var(--body-margin-sides);
display: grid;
/* prevents any body scroll -- good for dashboards */
overflow: hidden;
font-size: var(--body-fontsize);
grid-template-rows:
/* fake top margin */
var(--body-margin-top)
/* header */
auto
/* widget area */
1fr
/* fake bottom margin */
var(--body-margin-bottom);
}

fake-body-margin {
background: var(--body-margin-color);
}

header {
background: lightgreen;
text-align: center;
}

hr {
display: block;
margin: var(--body-margin-top) auto;
width: 100%;
border: 0;
border-top: 1px dashed black;
}

panels {
display: grid;
gap: 2em;
grid-template-columns: 60fr 40fr;
}

left-panel {
outline: 3px dotted green;
outline-offset: -3px;
display: grid;
grid-template-rows: auto 1fr;
}

left-panel-top {
/* Gap above Welcome blurb */
margin-top: 15px;
/* line separation is 1.4 x normal */
line-height: 1.4;
/* Gap beneath Welcome blurb */
margin-bottom: 0px;
}

left-panel-bottom {
position: relative;
display: grid;                    /* new */
gap: 1em;                         /* new */
grid-template-columns: 40fr 60fr;  /* new */
}

left-panel-bottom-content-1 {
background: orange;
border: 0;
border-radius: 5px;
column-gap: 10px;
display: grid;
grid-template-columns: auto auto;
max-height: 100%;
/* scroll the overflow */
overflow: auto;
padding: 0 0.5em;
/* prevents content height from affecting the layout*/
position: absolute;
width: fit-content;
}

/* NEW: a second scrollable list next to the first in the left panel */
left-panel-bottom-content-2 {
background: cyan;
border: 0;
border-radius: 5px;
column-gap: 10px;
display: grid;
grid-template-columns: auto auto;
max-height: 100%;
/* scroll the overflow */
overflow: auto;
padding: 0 0.5em;
/* prevents content height from affecting the layout*/
/* absolute is obviously wrong since it overlays content-1 */
position: absolute;
width: fit-content;
}

/* Hide scrollbar for Webkit browsers */
left-panel-bottom-content-1::-webkit-scrollbar {
display: none;
}

/* Hide scrollbar for IE, Edge and Firefox */
left-panel-bottom-content-1 {
-ms-overflow-style: none;
/* IE and Edge */
scrollbar-width: none;
/* Firefox */
}

scrollable-table-col1 {
height: fit-content;
}

scrollable-table-col2 {
height: fit-content;
}

scrollable-table-spacer {
padding-bottom: 6px;
}

/* Right-hand panel */
right-panel {
background: yellow;
border: 4px solid black;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}

/* Flex item inside right panel flexbox */
figure {
position: absolute;
width: 100%;
height: 100%;
background: transparent;
display: flex;
justify-content: center;
align-items: center;
}

.scaled-picture {
outline: 8px double black;
outline-offset: -8px;
max-width: 100%;
max-height: 100%;
}< /code>




Banner






Lorem ipsum odor amet, consectetuer adipiscing elit. Maecenas tempor
proin amet ad consequat tempor praesent facilisis. Tempus potenti
torquent nulla nullam elit class malesuada. Ut platea id ornare,
convallis fusce eros. Fringilla pretium porta phasellus consectetur
fermentum semper mollis. Est imperdiet euismod placerat et venenatis
mattis; magna dictumst integer.

Recent site updates:


















 






Подробнее здесь: https://stackoverflow.com/questions/794 ... -a-gridbox
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Как масштабировать изображение, чтобы вписаться в гибкую коробку в сетку
    Anonymous » » в форуме CSS
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous
  • Как сделать изображение вписаться на мобильный? HTML
    Anonymous » » в форуме Html
    0 Ответы
    5 Просмотры
    Последнее сообщение Anonymous
  • Как добавить гибкую и масштабируемую визуальную рамку из изображения?
    Anonymous » » в форуме CSS
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous
  • CSS равномерно распределяет элементы по двум строкам, сохраняя при этом гибкую ширину элементов.
    Anonymous » » в форуме CSS
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous
  • Как я могу сделать SVG в HTML вписаться в один экран без прокрутки?
    Anonymous » » в форуме Html
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous

Вернуться в «CSS»