gpt4 book ai didi

html - 达到最大高度后,如何使用 CSS 减小 div 的宽度?

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:04 24 4
gpt4 key购买 nike

我正在尝试创建一个可以包含未定义数量的对象的菜单;所述对象的大小取决于可用宽度(菜单的宽度)。菜单的高度永远不能超过一定值并且仍然包含所有子对象,这意味着子元素可以收缩,同时保持比例,但永远不会溢出“包含区域”。

像这样:

add = () => {
const menuObject = document.createElement('div')
menuObject.classList.add('menu-element')
const menu = document.getElementById('menu')
menu.appendChild(menuObject)
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}

button{
padding: 40px;
}

.bounds{
position: absolute;
border: 2px dashed black;
width: 10%;
right: 8px;
bottom: 8px;
height: 60%;
box-sizing: content-box;
}

.menu{
position: absolute;
width: 10%;
right: 10px;
bottom: 10px;

background-color: chocolate;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
}

.menu-element{
width: 100%;

background-color: dodgerblue;
margin: 5%;
}

.menu-element::before{
content: "";
padding-top: 100%;
display: block;
}
<body>
<button onclick="add()">Add item</button>
<div class="bounds">
Items should never leave this box
</div>
<div id="menu" class="menu"></div>

</body>

我已经尝试为菜单设置一个 max-height 属性,但这并没有修改它的宽度,它最终是控制整个大小调整模式的值。我正在寻找一个纯 CSS 的解决方案,如果可能的话,我们将不胜感激任何可以解决这个问题的线索。

最佳答案

如果您希望菜单包含在某些边界内,则应将其放置在这些边界内,以便它可以扩展到这些边界内。

由于菜单是 display: flex,我们可以通过向子元素添加 flex: 1 来让子元素共享菜单中的可用空间。

如果需要,我们可以选择向菜单项添加一个 max-height 值。

add = () => {
const menuObject = document.createElement('div')
menuObject.classList.add('menu-element')
const menu = document.getElementById('menu')
menu.appendChild(menuObject)
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

button {
padding: 40px;
}

.bounds {
position: absolute;
border: 2px dashed black;
width: 10%;
right: 8px;
bottom: 8px;
height: 60%;
box-sizing: content-box;
}

.menu {
width: 100%; /* Expand into boundaries */
height: 100%; /* Expand into boundaries */
background-color: chocolate;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-end;
}

.menu-element {
flex: 1; /* Makes elements expand into available space */
max-height: 25%; /* Height cap in case we want to have a set initial size */
width: 100%;
background-color: dodgerblue;
outline: 1px solid red; /* Help visualize boundaries */
}
<button onclick="add()">Add item</button>
<div class="bounds">
<div id="menu" class="menu"></div> <!-- Move menu into boundaries -->
</div>

关于html - 达到最大高度后,如何使用 CSS 减小 div 的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com