html 标记容器的 css
这是一个有点普遍的问题,但我的目标是在我的项目中使用最少的 css 来实现简洁的 html 标记,这已经困扰了我很长时间。
我经常使用具有固定大小的a
链接和背景图像的容器元素(例如:h1
)。
例如: 标记:
<h1 id="branding"><a href="site.com">Brand Name</a></h1>
Css:
h1#branding {
display:block;
width:200px;
height:50px
}
h1#branding a {
display:block;
width:200px;
height:50px;
text-indent:-999em;
background-image:url(path/to/img.png) no-repeat 0 0;
}
如您所见,我在 h1 和 a 元素上都包含了固定大小。我这样做是因为我过去在一些较旧的浏览器上看到过视觉问题,当时我没有为包含元素提供宽度和高度值。
我还使用此技术进行一些具有 结构的导航,并且必须向
ul
、li
和 a
元素添加尺寸,这使得 CSS 重复且冗长......
有更好的方法吗?
This is a bit of a general question but aim for concise html markup with minimal css in my projects and this is something that has bugged me for a long time.
I often use a container element (eg: h1
) with a fixed size a
link and background image.
EG:
Markup:
<h1 id="branding"><a href="site.com">Brand Name</a></h1>
Css:
h1#branding {
display:block;
width:200px;
height:50px
}
h1#branding a {
display:block;
width:200px;
height:50px;
text-indent:-999em;
background-image:url(path/to/img.png) no-repeat 0 0;
}
As you can see I include the fixed size on both h1 and a elements. I do this as I've seen visual issues in the past on some older browsers when I don't give the containing element the width and height values.
I also use this technique for some navigation with a <ul><li><a>..</a></li></ul>
structure and have to add dimensions to the ul
, li
and a
elements which makes the CSS repetative and lengthy...
...is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解您的要求,您可以将所有共享属性分配给各个元素使用的一个 CSS 类:
If I understand correctly what you asking, you could assign all the shared properties to one CSS class which the respective elements use:
为什么要通过 CSS 中的背景图像加载图像?为什么不简单地使用
![]()
标签?如果您想使用 CSS 精灵图像,我可以理解一点,但似乎您没有这样做(或者至少您的示例代码没有显示它)。使用![]()
标签使得无需使用display:block
并指定两次宽度和高度。然后,您只需为图像本身指定一次宽度和高度。例如:从 SEO 的角度来看,用
标签包围(我假设的)徽标也不是最佳实践。您应该为页面标题保留
标记,而不是公司或品牌名称。唯一可以做到这一点的页面是主页,但即使在那里我也不会这样做。
如果您想坚持使用 CSS 背景图像和徽标周围的
标记,那么您的 CSS 代码确实是正确的。
Why load the image via a background image in your CSS? Why not simply use an
<img>
tag? I can understand it a bit if you want to make use of CSS sprite images but it seems like you are not doing that (or at least your example code doesn't show it). Using an<img>
tag makes usingdisplay:block
and specifying the width and height twice unnecessary. You then only specify the width and height once for the image itself. E.g.:Surrounding the (what I assume) logo with an
<h1>
tag is also not the best practice from an SEO point of view. You should reserve the<h1>
tag for the page title, not the company or brand name. The only page where this could be done is the homepage but even there I would not do it.If you want to stick with using CSS background images and a
<h1>
tag around the logo then your CSS code is indeed correct.