Html CSS - 为什么我无法设置 <a href> 元素的高度和宽度?

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

CSS - Why am I not able to set height and width of <a href> elements?

htmlcss

提问by Kenny Bones

I'm trying to create css buttons by using the following html markup:

我正在尝试使用以下 html 标记创建 css 按钮:

<a href="access.php" class="css_button_red">Forgot password</a>

But it ends up being not bigger than the text in the middle. Even though I've set the class's height and width.

但它最终不会比中间的文本大。即使我已经设置了类的高度和宽度。

You can preview the problem here btw, www.matkalenderen.no Notice the first button, that's a form button and it's using it's own class. At first I tried to use the same class on the css button as well and the same problem appeared, so I tried to separate them into their own classes. In case there was some kind of crash. But it didn't matter anyway.

顺便说一下,您可以在这里预览问题,www.matkalenderen.no 注意第一个按钮,它是一个表单按钮,它使用自己的类。起初我也尝试在 css 按钮上使用相同的类,但出现了同样的问题,所以我尝试将它们分成自己的类。万一发生了某种崩溃。但无论如何都无所谓。

What am I missing here?

我在这里缺少什么?

回答by nickf

As the others have said, by default <a>is an inline element, and inline elements can't specify a width or height. You can change it to be a block element like this:

正如其他人所说,默认情况下<a>是内联元素,内联元素不能指定宽度或高度。您可以将其更改为块元素,如下所示:

a {
    display: block;
}

Though it will then display (unsurprisingly) as a block, sitting on its own, outside the flow of the surrounding text. A better solution is to use display: inline-blockwhich might be a best-of-both-worlds solution depending on your situation.

尽管它随后会(不出所料)显示为一个块,独立于周围文本的流动之外。更好的解决方案是display: inline-block根据您的情况使用可能是两全其美的解决方案。

See PPK's writeupabout it.

请参阅PPK关于它的文章。

The real use of this value is when you want to give an inline element a width. In some circumstances some browsers don't allow a width on a real inline element, but if you switch to display: inline-block you are allowed to set a width.

这个值的真正用途是当你想给一个内联元素一个宽度时。在某些情况下,某些浏览器不允许在真正的内联元素上设置宽度,但是如果您切换到 display: inline-block 您可以设置宽度。

回答by kingjeffrey

Because <a>'s are inline elements by default. In CSS define a { display:block; }and height and width settings will be applied.

因为 <a> 默认是内联元素。在 CSS 中定义a { display:block; }和高度和宽度设置将被应用。

Of course, you may not want to declare all anchor tags as block level elements, so filter by class or id as needed.

当然,您可能不想将所有锚标记声明为块级元素,因此请根据需要按类或 id 进行过滤。

回答by Crozin

I think the most proper solution is display: inline-block;which will allow you to set heightfor the element that still will be treated as inlineelement.

我认为最合适的解决方案是display: inline-block;允许您设置height仍将被视为inline元素的元素。