开发人员在编写 HTML 和 CSS 时最常犯的 6 个错误
属性placeholder
代替label
元素
请不要再使用placeholder
属性来代替label
元素。使用屏幕阅读器的用户无法填写输入字段,因为屏幕阅读器无法读取占位符属性中的文本。
<input type="email" placeholder="Enter your email">
我建议使用label
元素作为字段名称,placeholder
使用属性作为用户应填写的数据示例。
<label for="email">Enter your email</span>
<input id="email" type="email" placeholder="e.g. example@gmail.com">
img
装饰图形元素
我经常看到开发者把装饰性图形和内容图片混淆。例如,他们用 元素标记社交图标img
。
<a href="https://twitter.com" class="social">
<img class="social__icon" src="twitter.svg" alt>
<span class="social__name">Twitter</span>
</a>
但社交图标是装饰性图标,可以帮助用户更快地理解元素的含义,而无需阅读文本。即使我们删除图标,也不会失去元素的含义。因此,background-image
属性是最好的方法。
<a href="https://twitter.com" class="social">
<span class="social__name">Twitter</span>
</a>
.social::before {
background-image: url("twitter.svg");
}
resize: none
当你禁用调整文本区域大小的功能时,resize: none
可访问性会下降。这样用户就无法舒适地自行输入数据。
textarea {
width: 100%;
height: 200px;
resize: none;
}
您可以使用min-width
、max-width
和属性来限制元素min-height
的max-height
大小。用户可以以自己舒适的方式填写输入字段。
textarea {
min-width: 100%;
max-width: 100%;
min-height: 200px;
max-height: 400px;
}
使用或display: block
position: absolute
position: fixed
我经常看到下面的代码片段:
.button::before {
content: "";
display: block;
position: absolute;
top: 0;
left: 0;
}
这里display: block
没有必要,因为如果使用position: absolute
或position: fixed
浏览器display: block
默认设置的话。所以下面的代码是上一个代码的完整替代方案。
.button::before {
content: "";
position: absolute;
top: 0;
left: 0;
}
outline: none
我无法用键盘访问网站。我无法访问链接。我无法注册。这是因为开发人员在添加时禁用了元素的焦点outline: none
。
.button:focus {
outline: none;
}
/* or */
.button:focus {
outline: 0;
}
如果您需要禁用默认焦点,请不要忘记设置备用焦点状态。
.button:focus {
outline: none;
box-shadow: 0 0 3px 0 blue;
}
空元素
有一种做法是使用空的 HTML 元素来设置元素的样式。例如,汉堡包标记使用了空的div
orspan
元素:
<button class="hamburger">
<span></span>
<span></span>
<span></span>
</button>
.hamburger {
width: 60px;
height: 45px;
position: relative;
}
.hamburger span {
width: 100%;
height: 9px;
background-color: #d3531a;
border-radius: 9px;
position: absolute;
left: 0;
}
.hamburger span:nth-child(1) {
top: 0;
}
.hamburger span:nth-child(2) {
top: 18px;
}
.hamburger span:nth-child(3) {
top: 36px;
}
但是您可以使用::before
和::after
伪元素并实现类似的结果。
<button class="hamburger">
<span class="hamburger__text">
<span class="visually-hidden">Open menu</span>
</span>
</button>
.hamburger {
width: 60px;
height: 45px;
position: relative;
}
.hamburger::before,
.hamburger::after,
.hamburger__text::before {
content: "";
width: 100%;
height: 9px;
background-color: #d3531a;
border-radius: 9px;
position: absolute;
left: 0;
}
.hamburger::before {
top: 0;
}
.hamburger::after {
top: 18px;
}
.hamburger__text::before {
top: 36px;
}
.visually-hidden {
position: absolute !important;
clip: rect(1px, 1px, 1px, 1px);
width: 1px !important;
height: 1px !important;
overflow: hidden;
}
PS
✉️ 我通过电子邮件进行无限制的有关 HTML/CSS 的问答,预计 2 天内得到回复。
😎 我对您的非商业项目进行 HTML/CSS 审查并提出改进建议。
🧑🏫我帮助搜索有关 HTML/CSS 的高质量内容
请使用我的电子邮件进行沟通👉melnik909@ya.ru
💪从我这里发现更多免费的东西
文章来源:https://dev.to/melnik909/the-6-most-common-mistakes-developers-when-writing-html-and-css-f92