Setting a width and height on an A tag

181,570

Solution 1

You need to make your anchor display: block or display: inline-block; and then it will accept the width and height values.

Solution 2

You can also use display: inline-block. The advantage of this is that it will set the height and width like a block element but also set it inline so that you can have another a tag sitting right next to it, permitting the parent space.

You can find out more about display properties here

Solution 3

All these suggestions work unless you put the anchors inside an UL list.

<ul>
    <li>
        <a>click me</a>>
    </li>
</ul>

Then any cascade style sheet rules are overridden in the Chrome browser. The width becomes auto. Then you must use inline CSS rules directly on the anchor itself.

Solution 4

It's not an exact duplicate (so far as I can find), but this is a common problem.

display:block is what you need. but you should read the spec to understand why.

Solution 5

Below working for me

display: block;
width: 100%;
Share:
181,570

Related videos on Youtube

Luke
Author by

Luke

Updated on June 10, 2021

Comments

  • Luke
    Luke about 3 years

    Is it possible to set the width and height in pixels on an anchor tag? I'd like to have the anchor tag to have a background image while retaining the text inside the anchor.

    li {
      width: 32px;
      height: 32px;
      background-color: orange;
    }
    
    li a {
      width: 32px;
      height: 32px;
      background-color: red;
    }
    <li><a href="#">Something</a></li>
  • TheCuBeMan
    TheCuBeMan almost 8 years
    I was looking for a solution to set the width of the anchor tag as its text content and not in a certain width and height, so setting it to "inline-block" did the trick exactly. Thanks.
  • WhiteWalker
    WhiteWalker over 3 years
    +1, this works but can you please tell me the reason why display: block or display: inline-block; is making width and height work in this case?
  • MaBbKhawaja
    MaBbKhawaja over 3 years
    li is an inline tag and you cannot give width height properties to inline tags. Width height are not applicable on them it is as simple as that. When you give it display inline-block it starts to act as both inline and block and accepts block properties too.