Stop hyperlink inheriting div's width?

南笙酒味 提交于 2020-01-01 14:44:53

问题


Hi I have some hyperlinks inside a div with display:block. Problem is that the hyperlinks length when clicked is equal to the div's width. How do I make the hyperlink's clicked length equal to the text of the hyperlink only without specifying width for each link ? JSFiddle here


回答1:


Use

#links a {clear:left;float:left}

The float will allow the link to be sized, and the clear will prevent the links from being on the same line.

You may need to add a clear:left to the #links container depending on your design.

EDIT

A little tutorial since you asked:

There are two types of elements, inline and block. Inline ones show in a line with no breaks. Block elements take up the whole line and move to the next one.

Inline elements can't have their width or height styled. Blocks can.

<a> is an inline element. By setting its display to block, you tell it to make a new line every time.

float gives elements inline behavior so they bump up next to eachother and flow over onto the next line. float also allows you to style the width/height of the element. It's sort of a mix between the two.

The clear attribute stops the inline floating and goes back to normal block behavior (new lines every time).

You won't need display:block and float: at the same time.

Another solution would involve display:inline-block, but this is not supported in several browsers so isn't encouraged (although I find it pretty handy).




回答2:


set the link style to display:inline-block; (not supported in elder IE6) or float it with float:left; or float:right;




回答3:


display: block; is what makes the link elements expand to their parent width. By default, link elements are in-line elements, not block elements.

Simply remove that declaration and your problem should be gone.

JSFiddle example




回答4:


Do you mean something like this:

<a href="example.com" style="text-decoration: none;">Foo</a>



回答5:


width:auto?

Or try display:inline;

on the links

it shouldnt get the divs width then



来源:https://stackoverflow.com/questions/4322029/stop-hyperlink-inheriting-divs-width

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!