Explain Codes LogoExplain Codes Logo

Setting a width and height on an A tag

html
responsive-design
css-properties
accessibility
Nikita BarsukovbyNikita Barsukov·Dec 4, 2024
TLDR

To set a width and height on an <a> tag, apply display: inline-block or display: block. Here's a quick example:

<a href="#" style="display: inline-block; width: 100px; height: 50px;">Link</a>

This makes the <a> element behave like a block-level element, respecting the specified dimensions while preserving its inline document flow.

Decoding display: block and display: inline-block

The display property is your control board for managing how your <a> tag behaves in the HTML document layout. Set it to inline-block and your tag can snuggle up next to other inline elements, accepting specified width and height. Switch it to display: block, and your tag becomes a level-headed block, taking up the full width of its parent, unless told otherwise.

When creating list-based navigation menus, setting display: block on your <a> tags makes them fill up the entire horizontal space within a list item, creating more generous click targets.

Taking styles out of line

While inline styles are neat and direct, they can get messier as your project grows. To keep your code base maintainable, consider moving your styles to an external stylesheet, freeing your HTML from style overload and making your styles reusable:

/* Useful class for reusable link styles */ .custom-link { display: inline-block; /* No space problems here */ width: 100px; /* Nice and wide */ height: 50px; /* Not feeling short */ text-align: center; /* All lined up */ line-height: 50px; /* Reach for the top */ background: url('bg.jpg') no-repeat center / cover; /* Fancy background */ }

Apply the power:

<a href="#" class="custom-link">Link</a>

Responsive helpers

Nobody likes unnecessary scrolling. Use relative units like rem, em, or % to make sure your links scale nicely across different device sizes and browser settings.

Cross-browser consistency

Remember, not all browsers are created equal. Always check if your CSS properties play nice across different browsers.

Accessibility isn't optional

Ensure your links are easy to click and view, especially for users with different abilities. This means large clickable zones, adequate contrast between text and background, and clean, semantic HTML for screen readers.