Can I "override" the width of an HTML element with CSS?
I'm doing some work with CSS, and I have an <li>
element with a <div>
element inside of it. The <div>
element assumes the width of the enclosing <li>
element, but the text content inside the <div>
is wider than the <li>
(and therefore goes onto two lines). What I want to do is make the <div>
the same width as its longest text element, does anyone know how I can do this? Thanks.
<ul style="display: inline-block; list-item-style: none">
<li id="foo" style="float: left; list-style-type: none; position: relative;">
<a href="...">brief text</a>
<div id="bar" style="position: absolute; width=???">
<ul>
<li>a long chunk of text</li>
<li>an even longer piece of text</li>
</ul>
</div>
</li>
</ul>
R开发者_如何学Goight now, the width of div#bar
is equal to 100% of the width of its enclosing element, li#foo
, and the width of li#foo
is equal to the width of the text in its <a>
tag (plus padding and borders). What I want to do is make div#bar
be the width of <li>an even longer piece of text</li>
, but I can't figure out how to accomplish that, even with Javascript.... or am I going to be forced to use an absolute measurement for the width? Any advice would be greatly appreciated.
Strip out the position attributes from #foo and #bar.
Then add:
<style type="text/css">
#bar li { white-space:nowrap !important; }
</style>
put !important
after the style value before ;
Sample:
#element{ width:500px!important;}
try
width:500px
instead of width=500px
(replace 500 with desired width)
http://jsfiddle.net/p4YNA/
<ul style="display: inline-block; list-item-style: none">
<li id="foo" style="float: left; list-style-type: none; position: relative;">
<a href="...">brief text</a>
<div id="bar" style="float:left;">
<ul>
<li>a long chunk of text</li>
<li>an even longer piece of text</li>
</ul>
</div>
</li>
</ul>
If you can remove the display: inline-block from the outer <ul/>
and remove float: left from the foo <li/>
then the list will expand to the longest element.
A solution could be to use a fixed width for the #bar
. A second solution is to remove position:absolute;
from #bar
.
According to the specification, you can can't (see edit) overide it by using a combination of rules that is stronger than the element style.
Element style (style="XXX") = 1000
Id (#id) = 100
Class (.class) = 10
element (ie: p) = 1
So if you are able to specify a css rule with more than 1000, I think you could do it.
EDIT: After some test, if found that a style defined directly in an element can't be overiden by css with this method. Sorry.
精彩评论