Recently I was building a new website for myself, and I came up with some effects, but encountered some minor troubles during implementation, such as this inline block. Fortunately, most of the problems have been solved, so I wrote them to share.
When we are making web pages, we sometimes want an element to be able to define width and height like a block, and also be able to run continuously like a normal inline. For example, the place marked by the red line in the picture below:
Usually we use code like this to achieve such an effect:
Example Source Code
[www.downcodes.com] <a href=”#”><img src=”….” alt=”….” /></a>
Although this can achieve the goal, the code is still not refined enough and flexible enough. In an ideal way, we can achieve it with just the following code:
Example Source Code
[www.downcodes.com] <a href=”#”>Yangliu.name</a>
In this case, we need to specify width height and background-image for the a tag. However, the default display attribute of the a tag is inline, and width and height are invalid. And if display:block is set to a, although the width and height problem can be solved, the element will automatically break lines and cannot achieve the effect we need. Is there any way to achieve the same thing as the img tag, which can set the height and width without automatically breaking the line?
The answer is yes. Opera and Webkit support a CSS2 property display: inline-block. Using this attribute, we can fully achieve the effect we need under Opera, but it will not work under other browsers.
The display attribute also has a less commonly used value display: inline-table. Using this value can also fully achieve the effect we need. This property is correctly supported by all browsers except IE, but... well, IE again. Although all Web Developers will hate it when faced with CSS, giving up IE is equivalent to giving up 70% of users, so we still have to find other solutions.
I had no choice but to Google it, and I actually found it. As pointed out in this article, if you first trigger IE's hasLayout, and then set its display: inline, this element will become inline-block! In this way, we can take advantage of this unreasonable feature of IE and combine it with some CSS Hacks, giving CSS codes compatible with various browsers:
Example Source Code
[www.downcodes.com] .element-class {
display: -moz-inline-stack; //Firefox only code
display: inline-block; //some standard browsers
zoom: 1; //IE only
*display: inline; //Only IE know this code (CSS Hack)
}
Through this code, you can achieve inline-block that behaves consistently in various browsers. However, this method has a small drawback, that is, it cannot pass W3C CSS verification. Of course, it is also very simple to pass the verification. You can issue a style sheet with the inline-table attribute to browsers other than IE, and issue a separate IE Only CSS for IE.