Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

html - Why does display:block not stretch buttons or input elements

I'm trying to understand the reason behind this problem:

What's the underlying reason behind <button> or <input> elements not behaving like other elements when set to display:block!

I'm not looking for workarounds to fix this problem, so please don't point me to this answer because it doesn't answer the question.

Here's a js-fiddle that illustrates the problem

Update 1: @Pete is correct, the default size attribute of an element is what sets the size even on block, as you can in this fiddle the size and cols attribute of <input> and <textarea> changes their width. That solves part of my question.

With that in mind, my question is now, why is the <button> element not behaving like other block elements? It's a mystery to me!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Button, Input and other form elements are actually replaced elements - see this answer: HTML5: Non-replaced vs. replaced element?

Additionally, button and input are inline elements. Thus, reading the MDN docs regarding visual formatting here: https://developer.mozilla.org/en-US/docs/Web/CSS/Visual_formatting_model, as well as the w3c docs here: https://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width, you can conclude that for replaced inline elements:

If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic width, then that intrinsic width is the used value of 'width'.

Therefore, button and input have an intrinsic width set to their content (or the size attribute on input, if used). That's why just specifying display: block doesn't do anything to the size of a button or input. You also have to override the intrinsic width of the elements.


Update: While researching more after answering this question, I found a much older answer which goes into much more detail about this same issue. You can find it here: https://stackoverflow.com/a/27605483/630170.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...