Html 防止 div 占据 100% 的宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3794770/
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 04:38:37  来源:igfitidea点击:

prevent div's from taking 100% width

htmlcss

提问by Samuel

<div style="position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px;">

  <div style="
         border: 2px solid black;
         margin: 0 auto;
         text-align: center;
         padding: 3px;">

    Hello<br />Hola

  </div>

  <div style="
         border: 2px solid black;
         margin: 0 auto;
         text-align: center;
         padding: 3px;">

    Another Sentence

  </div>

</div>

I have a problem: the borders of the inner div's reach over the whole width of the page, but i want them to only frame the content inside them. If i use: display: inlinethe borders frame each line separately and overlap, so that doesn't work - can somebody help?

我有一个问题:内部 div 的边框覆盖页面的整个宽度,但我希望它们只框住它们内部的内容。如果我使用:display: inline边框分别框住每条线并重叠,所以这不起作用 - 有人可以帮忙吗?

P.S the style's aren't declared like this in the original document but in a stylesheet

PS 样式在原始文档中不是这样声明的,而是在样式表中声明的

回答by meder omuraliev

Assign a width to the absolutely positioned element? If you're looking for shrink-wrapping, float:leftor display:inline-blockare perfect for that.

为绝对定位的元素分配宽度?如果您正在寻找收缩包装,float:left或者display:inline-block是完美的选择。

回答by Nikita Rybak

Try display:inline-block, it always helps me in situations like this.

Try display:inline-block,它总是在这种情况下帮助我。

http://jsfiddle.net/FaYLk/

http://jsfiddle.net/FaYLk/

回答by David Lawrence

Its not as simple to just do:

这样做并不简单:

display: inline-block;

You must do more than that to cross browser this.

你必须做更多的事情来跨浏览器。

display: inline-block;
display: -moz-inline-stack; /* for firefox 2 */
*display: inline; /* for ie 6 and 7 */

回答by James111

Put a container around all the content. E.g

在所有内容周围放置一个容器。例如

<div class='container'> <div>I wont be 100%</div> <div>Nor will I :)</div> </div>
.container{ display: inline-block; }