更新
看起来我可能没有很清楚地展示Plunker,因为Anthony Rutledge显然没有看到(或者忽略了)它。我提供了一张截图,并给出了一些关于如何使用Plunker的提示。
PLUNKER - 嵌入
PLUNKER - 信息
PLUNKER - 预览
![Plunker iNFO](https://istack.dev59.com/OKJMS.webp)
问答
这引出了一个简单的问题:更改HTML元素的默认显示属性是一种不好的做法吗?
不,不是。事实上,这是Web开发人员(包括我自己)经常进行的一种做法,不仅更改元素的属性,还有属性和内容等。
这是否违反标准,应该尽可能避免?
不,但也许做法本身可能会破坏代码,这比标准更重要。标准当然很重要,但并非必不可少。如果这是情况,那么Web浏览器应该遵守一个共同的标准(我在和你说话,IE :P)。以下是应该避免的几个事项:
Using the table element for a layout
<table>
<tbody>
<tr>
<td><img></td>
<td><input type="button"/></td>
</tr>
...
Using inline styles
<div style="display: inline-block"></div>
Using inline event handlers
<div onclick='makeASandwich();'></div>
“对于编程来说,只要代码语义正确(例如标题放在h1中,文章放在article中等),那么更改元素的显示属性是非常微小但基本必要的方面。所以,我想它可以被认为是‘面包和黄油’,这使得语义学成为‘作为装饰品使用的欧芹而从未被食用的东西’。
语义学是主观的,是一种思维方式,而不是标准。我认为初学者应该意识到它的重要性(或者至少了解它对其他人的重要性),但不应该在
<article>
和
<section>
之间进行死板的辩论,哪一个在语义上比使用
<main>
和
<aside>
更好。随着时间的推移,语义学会变得‘自然而然’。”
方法一:使用display:inline
我从未找到过使用display:inline
的好理由,因为display:inline-block
是一个更好的选择。
方法二:使用float
浮动是易碎的古董。就像处理奶奶的骨瓷晚餐盘一样,如果你打算使用它们,必须采取某些预防措施。要注意如何清除浮动,不要把它们扔进洗碗机。
基本上,如果只有这两个选项,方法一是更好的选择,特别是如果使用inline-block
。我会避免使用floats
,它们很反直觉并且容易出问题。我记得只用过一次,因为客户想要文字环绕图片。
CSS & CSS/JS
Provided is a Snippet comprising of 3 demos:
Pure CSS solution utilizing display: flex
.
Pure CSS solution utilizing display: table-row
/table-cell
.
CSS and minimal JavaScript solution utilizing display: inline-block
and the classList
API
Each of these demos are identical on the surface:
HTML
<section id="demo1" class="area">
<header class="titles">
<h1>Demo 1 - </h1>
<h2>display: flex</h2>
</header>
</section>
This is the original markup with the following changes:
This is a good example of semantics: Everything has meaning
You'll notice at the bottom of the viewport, are buttons. Each button corresponds to a demo.
Details on how each demo works as well as pros and cons are in the following files located in the leftside menu of the Plunker (see screenshot):
- demo1.md
flexbox
- demo2.md
disply: table
- demo3.md
classList
PLUNKER
These notes are not for the purpose of informing the OP of anything relevant to the question. Rather they are observations that I would like to address later on.
Further Notes
- Demo 1 and demo 2 are powered by the pseudo-class
:target
. Clicking either one of them will trigger the click
event It resembles an event because it's invoked by a click
, but there's no way of controlling, or knowing the capture or bubbling phase if it actually exists. Upon further clicking of the first and second button, it will exhibit odd behavior such as: toggling of the other button then eventually becoming non-functional. I suspect the shortcomings of :target
is that CSS handles events in a completely different way with little or no interaction with the user.