文本区域和按钮设置为宽度 90% 和 10%,但包装在 Flex 容器中[重复]

问题描述 投票:0回答:2

我希望输入框和发送按钮框在 Flex 行中彼此并排,输入占据 90% 的宽度。但是,发送按钮位于输入下方,我不确定为什么。

.chatFooter { /* footer */
  width: 100%;

  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;

  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  -o-box-sizing: border-box;
}
.chatInput {
  height: 100%;
  width: 90%;
  outline: none;
  resize: none;
  font-size: 1em;
  font-family: inherit;
  background-color: white;
}
.chatSendBtn {
  height: 100%;
  width: 10%;
  font-size: 1.3em;
  background-color: white;
  color: black;
  cursor: pointer;
}
.chatSendBtn:hover {
  color: red;
}
<div class="chatFooter">
  <textarea
     class="chatInput"
     placeholder="Enter message"
  ></textarea>

  <div class="chatSendBtn">
    Send
  </div>
</div>

编辑:我在最初的问题中在元素上添加了边框,这样更容易看到发生了什么,但是包装按钮的原始问题没有任何按钮,我已经删除了边框。

html css flexbox
2个回答
2
投票

这是因为标准 CSS 盒模型 的工作方式。在标准 CSS 盒模型中,内边距和边框不包含在设置的尺寸中。它们被添加到设置值中,这会增加元素的总大小。您已经在要添加到设置宽度(即 90% 和 10%)的元素周围设置了边框,这使得它们比容器更大并导致它们换行。

这里

默认情况下,在 CSS 盒模型中,您分配给对象的宽度和高度 元素仅应用于元素的内容框。如果元素 有任何边框或填充,然后将其添加到宽度和高度 以获得在屏幕上呈现的框的大小。

要解决这个问题,请将

box-sizing: border-box;
添加到元素中。当您添加 box-sizing 并将其设置为 border-box 时,宽度和高度属性包括内容、填充和边框。更多- 盒子尺寸

.chatFooter { /* footer */
  width: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;

  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  -o-box-sizing: border-box;
  border: 1px solid red;
}
.chatInput {
box-sizing: border-box;
  border: 1px solid black;
  height: 100%;
  width: 90%;
  outline: none;
  resize: none;
  font-size: 1em;
  font-family: inherit;
  background-color: white;
}
.chatSendBtn {
box-sizing: border-box;
  border: 1px solid black;
  height: 100%;
  width: 10%;
  font-size: 1.3em;
  background-color: white;
  color: black;
  cursor: pointer;
}
.chatSendBtn:hover {
  color: red;
}
<div class="chatFooter">
  <textarea
     class="chatInput"
     placeholder="Enter message"
  ></textarea>

  <div class="chatSendBtn">
    Send
  </div>
</div>


0
投票

删除宽度值并停止尝试控制所有像素。由于您使用的是 Flex,因此最简单的方法是让系统为您进行分数数学运算。弹性单位的总和是在使用

display: flex;
的父级的子级中计算的。在本例中,9+1=10,因此将 9/10 的空间分配给输入,将 1/10 的空间分配给按钮如下:

.chatInput {
  flex: 9;  /* instead of width: 90%; */
}
.chatSendBtn {
  flex: 1;  /* instead of width: 10%; */
}

在这个系统中,你不必巧妙地处理盒子模型。您可以自由应用边距填充和边框,并且您的弹性单元将自然地应用于元素。

为了美观,您可能希望将它们在父容器中垂直居中。

.chatFooter {
  align-items: center;  /* or maybe try top, depends how you like it */
}
© www.soinside.com 2019 - 2024. All rights reserved.