首页 > 解决方案 > div 内 100% 宽度的输入与 div 重叠

问题描述

我在宽度为 100% 的输入中遇到边距问题,因为它与 div 容器重叠。

我在论坛上寻找解决方案,可能的解决方案是应用 box-sizing:border-box,但它不起作用。

解决方案对我不起作用:CSS - 100% 宽度的输入与 div 重叠

jsfiddle: https://jsfiddle.net/igorac1999/fuovpkba/

html {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

*, *::before, *::after {
  -webkit-box-sizing: inherit;
  -moz-box-sizing: inherit;
  box-sizing: inherit;
}

body, pre {
  margin: 0;
  padding: 0;
}

.container {
  width: 100%;
  max-width: 980px;
  margin: 0 auto;
}

.container_calculator {
  width: 100%;
  max-width: 400px;
  background-color: tomato;
  border-radius: 5px;
  margin: 5px auto;
}

.container_calculator > label {
  display: inline-block;
  color: #fff;
  margin: 10px 0 0 20px;
}

.container_calculator > input {
  height: 20px;
  border: 1px solid tomato;
  border-radius: 5px;
  width: 100%;
  margin: 5px 20px;
}


div.result_bin2dec {
  border: 1px solid #edf2f7;
  background-color: #edf2f7;
  border-radius: 10px;
  margin-top: 30px;
  height: 35px;
}
    <div class="container">
        <div class="container_calculator">
            <label>Number</label>
            <input type="text" id="number">
        </div>

        <div class="result_bin2dec">
            <pre>
                Dec: 10
                Bin: 01
            </pre>
        </div>
    </div>

在此处输入图像描述

标签: htmlcss

解决方案


而不是margin在孩子上,你可以padding在 parent 上使用,所以它可以包含在box-sizing


如您所说的链接答案中指定的对您不起作用,请参阅下面的 box-sizing 规范链接以了解它的工作原理以及如何使用它


可能的例子:https ://jsfiddle.net/gr7cbevj/

html {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

*,
*::before,
*::after {
  -webkit-box-sizing: inherit;
  -moz-box-sizing: inherit;
  box-sizing: inherit;
}

body,
pre {
  margin: 0;
  padding: 0;
}

.container {
  width: 100%;
  max-width: 980px;
  margin: 0 auto;
}

.container_calculator {
  width: 100%;
  max-width: 400px;
  background-color: tomato;
  border-radius: 5px;
  margin: 5px auto;
  padding: 0 20px;/* added */
  box-sizing: border-box;/* added */
}

.container_calculator>label {
  display: inline-block;
  color: #fff;
  margin: 10px 0 0 0px;/* modified */
}

.container_calculator>input {
  height: 20px;
  border: 1px solid tomato;
  border-radius: 5px;
  width: 100%;
  margin: 5px 0px;/* modified */
}

div.result_bin2dec {
  border: 1px solid #edf2f7;
  background-color: #edf2f7;
  border-radius: 10px;
  margin-top: 30px;
  height: 35px;
}
<div class="container">
  <div class="container_calculator">
    <label>Number</label>
    <input type="text" id="number">
  </div>

  <div class="result_bin2dec">
    <pre>
                Dec: 10
                Bin: 01
            </pre>
  </div>
</div>

请参阅box-sizing的使用。

CSS 属性设置如何计算元素的box-sizing总宽度和高度。


推荐阅读