开发者

Function-like CSS Classes

EDIT: I apologize if this has been asked before or is a well-known techinque. I didn't know what this would be called and hence I was unable to search for it.

In my HTML document, I vertically center something as follows:

<div style='position:  absolute; margin:  auto; top:  0; bottom:  0; height:  500px'>
<!-- CONTENT HERE -->
</div>

This works great, the only problem is, the code isn't quite reusable because it depends on the particular height of the block. What I would like to do is something like this:

<div class='vcenter(500px)'>
<!-- CONTENT HERE -->
</div>

.vcente开发者_JAVA百科r(height)
{
    position:  absolute;
    margin:  auto;
    top:  0;
    bottom:  0;
    height:  height;
}

If I could implement something like this, then I would not have to duplicate code every time I wanted to vertically center something. Does CSS have a way of implementing this?


You're not happy with doing it this way?

<div class='vcenter' style='height: 500px'>
<!-- CONTENT HERE -->
</div>


You could use a css expression, but dont. It's badly supported by browsers and bad practice.

I would recommend using a css generating tool: http://lesscss.org/ or http://compass-style.org/


There is no way of doing this with native CSS. I suggest looking at a Javascript solution.

A jQuery solution would look something like this:

$(function(){
    $(window).resize(function(){
        var newHeight = $(window).height() * someRatio;
        $("#yourElement").css('height', newHeight);
    });
});


Use two classes.

<div class="universal specific-style">
  <!-- content -->
</div>

Where .universal and specific-style should have more semantic names. Then, in your stylesheet:

.universal {
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
}

.specific-style {
  height: 200px;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜