Html 如何防止填充的子元素溢出其父元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10965365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:55:29  来源:igfitidea点击:

How to prevent padded child element to overflow its parent?

htmlcsswidthpadding

提问by Ricardo Rodrigues

As you can see from this example, the inputseems to "overflow" its parent div. I'd like to add padding to the inputwithout making it overflow its parent.

正如你从这个例子中看到的,input似乎“溢出”了它的父级div。我想在input不使其溢出其父项的情况下添加填充。

I would like to know the best solution/workaround for every browser (including IE, Firefox, Chrome, etc).

我想知道每个浏览器(包括 IE、Firefox、Chrome 等)的最佳解决方案/解决方法。

回答by Fong-Wan Chau

You can see this answer, but if you don't like it, you can use box-sizingCSS3 property like this:

你可以看到这个答案,但如果你不喜欢它,你可以box-sizing像这样使用CSS3 属性:

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

Live jsFiddle example

实时 jsFiddle 示例

回答by webdevkit

Padding adds to the width of your object. One option would be to remove the left/right padding from the input and just use text-indent, although this removes the right padding.

填充会增加对象的宽度。一种选择是从输入中删除左/右填充并仅使用文本缩进,尽管这会删除右填充。

.inside{
    background: blue;
    border: none;
    padding-bottom: 10px;
    padding-top: 10px;
    text-indent: 10px;
    width: 100%;
}

Alternatively, instead of using hardcoded pixel-widths for your padding, you could use percentages, and subtract that value from the width:

或者,您可以使用百分比,而不是使用硬编码的像素宽度作为填充,并从宽度中减去该值:

.inside{
    padding: 3%;
    width: 94%;
}

回答by sachleen

Don't specify the width of the inside div as 100%. A div will automatically fit the width of its parent container. Demo

不要将内部 div 的宽度指定为100%. div 将自动适应其父容器的宽度。演示

回答by GrantVS

Looks like the input is inside the div but is located in the top left corner. Because the input takes-up 100% of the div's width it obscures the red background of the div. The div is longer so it sticks out the bottom making it seem like the input is on-top. Do the following:

看起来输入在 div 内,但位于左上角。因为输入占据了 div 宽度的 100%,它遮住了 div 的红色背景。div 更长,所以它伸出底部,使输入看起来像在顶部。请执行下列操作:

  • Apply the padding to the CSS of the outside div not the input box.
    You could apply a margin to the input if you want but I think padding the containing div is better.
    • Make the input box less wide than the div (<100%)
  • 将填充应用于外部 div 的 CSS,而不是输入框
    如果需要,您可以对输入应用边距,但我认为填充包含的 div 更好。
    • 使输入框的宽度小于 div (<100%)