CSS:元素的复杂宽度规则

时间:2011-04-28 14:32:08

标签: css

我会告诉你究竟是什么的解释,但是有可能有一个具有以下内容的元素:

如果屏幕小于600px那么元素将是宽度:100%; 如果屏幕大于640px,则元素具有可变宽度,但左侧和右侧的边距为20px。 在600到640像素之间,边距从20px变为0px。当屏幕宽度为620时,理想情况下是步进的,边距降至10px等。 此外,当屏幕大于1000px时,宽度保持固定,并且元素保持居中。

我的css知识是基本的。我自己可以轻松实现任何这些,但是在一起?我正在寻找javascript解决方案,但作为最后的尝试,我在这里问一个很好的解决方案。

由于

4 个答案:

答案 0 :(得分:3)

请参阅:http://css-tricks.com/resolution-specific-stylesheets/

这适用于大多数现代浏览器。

答案 1 :(得分:0)

这里有两个选项。

选项1 :坚持600px的固定宽度,让它自动居中。

要执行此操作,只需将以下行添加到CSS中以获取最外层的DIV标记:

margin: 0 auto;

选项2 :这是使用JavaScript。您可以先使用CSS设置最外层DIV的min-width属性。然后让JavaScript进行条件计算。

就个人而言,我会选择选项1。

答案 2 :(得分:0)

下面是我为儿子的棒球队制作的网站布局的CSS和HTML。布局与您想要的类似。

<强> CSS

/* page element and contents */
#page
{
    overflow:auto;
    height: 100%;
}
#centerContent
{
    position: relative;
    overflow: hidden;
    height: 100%;
    width: 66%;
    min-height: 430px;
    min-width: 778px;
    margin: 0px auto;
    border-left-style: ridge;
    border-right-style: ridge;
    border-left-width: 5px;
    border-right-width: 5px;
    border-right-color: #f6e662;
    border-left-color: #f6e662;
}

#leftMargin
{
    position: absolute;
    overflow: hidden;
    left: 0px;
    top: 0px;
    height: 100%;
    width: 17%;
    border-right-width: 5px;
    text-align: center;
}
#rightMargin
{
    position:absolute;
    overflow:hidden;
    right:0px;
    top:0px;
    height:100%;
    width:17%;
    border-left-width: 5px;
}

/* header element and contents */
#header
{
    overflow:hidden;
    background-color: #FFFFFF;
    border-bottom: solid 1px #053c01;
    height:75px;
    top: 0px;
    left: 0px;
}
/* main element and contents. */
#main 
{
    position:absolute;
    overflow:hidden;
    background-color: #FFFFFF;
    top: 76px;
    bottom: 25px;
    left: 0px;
    right: 0px;

}
/* footer element and contents */
#footer
{
    position:absolute;
    overflow: hidden;
    background-color: #FFFFFF;
    border-top: solid 1px #053c01;

    height: 25px;
    bottom: 0px;
    left: 0px;
    right: 0px;
}

<强> HTML

<div id="page">
  <div id="leftMargin">
  </div>
  <div id="centerContent">
    <div id="header">
    </div>
    <div id="main">
    </div>
    <div id="footer">
    </div>
  </div>
  <div id="rightMargin">
  </div>
</div>

答案 3 :(得分:0)

您可以在现代浏览器中使用媒体查询实现这一目标,而不是在IE8或更早版本中。例如,你有:

@media screen and (max-width:600px) {
    #divID {width:100%;}
}

如果屏幕宽度不足600px,那么名为divID的id的div宽度为100%。

您可以设置大小之间的条件,如下所示:

media screen and (min-width: 601px) and (max-width:640px) {
    #divID {width:auto;}
}

您可以设置宽度超过一定大小的设置:

@media screen and (min-width: 601px) {
        #divID {width: 500px;}
}