Can someone explain me this?
<html>
<head>
<title>QUESTION</title>
</head>
<body>
<p>Why Link is centered, but Button is not?</p>
<a style="display: flex; justify-content: center;">LINK</a>
<button style="display: flex; justify-content: center;">BUTTON</button>
</body>
</html>
8 Replies
Some browsers doesn't accept change of the display property on button element.
Why do you need to have button as flex container?
It's a similar reason to why the button has a background and a border while the link doesn't; user-agent styles.
I've had a look through FireFox's UA sheets and can't figure out exactly why, but you can generalise it as;
- buttons and links both prefer to be as small as possible
- links will prefer to fill horizontal space in some situations
Flex can be set & used on a button, try these;
Yea, but he want to center button relative to body element like link anchor element.
If you apply display property to button, it doesn't take full width of the body element.
What's happening with the anchor is not that the anchor is being centered, it's that the content of the anchor is centered.
Likewise, to center a button itself, it needs a parent which is centering it's content;
Applying
display: flex
to an element & doing any flex styling means you are acting on the layout of that element's children, which includes text nodes.I know, the anchor element is set as flex container and content of this container is centered. The difference is that if you set flex value on property display on anchor element, the anchor element will take full width of it's containing block. If you set flex value on property display on button element, the button element won't take full width of it's containing block. I consider that this behaviour is different for button element.
you're right, it's to do with UA styles. My guess would be that it's specific to input-like elements as they use a lot of lower level interactivity with the browser & OS unlike textual elements which are pretty much just text.
It's more than just CSS which is doing this to buttons as there's nothing in the UA styles other than the
appearance
which could effect the behavior
@armands.uiska is there anything here you'd like more detail on or any follow up questions you have?My question was not like real question... I understand that browser treats button and link differently. It was just strange to me that button and link (even they are inline elements) are treated differently when using display: flex; button is not stretched - you need to manually set width: 100%
And thanks for some thoughts and answers
yeah it's pretty strange, it comes down to low level browser stuff which I don't understand well enough to properly explain.