Html 覆盖 <div> 内联宽度样式以使元素拉伸到内​​容?

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

Overriding <div> inline width style to make element stretch to contents?

htmlcsswidthcss-tables

提问by CodeMoose

Working on reskinning a client's intranet. I can't modify existing HTML, only provide an override stylesheet.

致力于重新设计客户的 Intranet。我无法修改现有的 HTML,只能提供一个覆盖样式表。

Within the HTML is a body content wrapper - any time the window is resized, it gets an explicit width and height set inline to the window width and height:

在 HTML 中是一个正文内容包装器 - 任何时候调整窗口大小时,它都会得到一个明确的宽度和高度,内嵌到窗口宽度和高度:

<div id="s4-workspace" style="height: 660px; width: 1331px;">

Now, some pages have a large table within this content wrapper (at least 1600px wide) and when the window is smaller than this, the table breaks out of the container leaving behind all background and padding. All other elements obey the wrapper width, creating a whole bunch of negative space when scrolling right:

现在,有些页面在这个内容包装器中有一个大表格(至少 1600 像素宽),当窗口小于这个值时,表格会脱离容器,留下所有背景和填充。所有其他元素都遵循包装器宽度,向右滚动时会产生一大堆负空间:

enter image description here

在此处输入图片说明

Is there a way to override the inline width and allow the container div #s4-workspaceto stretch to its contents? My best guess was setting width: auto !important;, but chrome and firefox still prioritize the inline style. Any help is appreciated.

有没有办法覆盖内联宽度并允许容器 div#s4-workspace拉伸到其内容?我最好的猜测是设置width: auto !important;,但 chrome 和 firefox 仍然优先考虑内联样式。任何帮助表示赞赏。

回答by cimmanon

In your specific instance (overriding width/height to prevent content overflow), changing the display type will do what you need:

在您的特定实例中(覆盖宽度/高度以防止内容溢出),更改显示类型将满足您的需求:

http://cssdeck.com/labs/kfpnpruw

http://cssdeck.com/labs/kfpnpruw

<div class="foo" style="width: 400px; height: 300px;">
  Foo
  <img src="http://placekitten.com/600/300" /><!-- 600x300 image -->
</div>

.foo {
  background: yellow;
  display: table-cell;
  padding: .5em;
}

Elements set to table-cell will treat width and height properties as a suggestedvalue, rather than an absolute value.

设置为 table-cell 的元素会将宽度和高度属性视为建议值,而不是绝对值。

回答by raam86

You can override element inline style like this:

您可以像这样覆盖元素内联样式:

div[style] {
   background: yellow !important;
    height: auto!important
}

Check out this fiddle

看看这个小提琴