2

是否有一种“css”方式可以使居中的 div 表现得好像它有一个最小的左边距?我希望一个居中的 div 以页面为中心,除非该页面的宽度小于某个值。类似于以下内容:

.centred { width: 400px; margin: 0 auto; min-margin-left: 200px; }

我知道 min-margin-left 不存在,但我怎么能做到这一点?下面是图片中的示例。认为灰色边框是浏览器,蓝色框是我的“中心”div。

当页面足够宽时居中

页面不够宽时的左边距

4

3 回答 3

1

For something like this we can use CSS Media Queries.

.centred { width: 400px; margin: 0 auto; }

@media screen and (max-width:800px) {
    .centred { margin-left:200px; }
}

In this example, all devices which have a display with under 800px width will be given the 200px margin-left.

Alternative Solution Without Media Queries

An alternative solution to this would be to display your content as a table and give the containing cell a padding of 200px.

<div class="table">
    <div class="table-cell">
        <div class="content">
        </div>
    </div>
</div>
.table {
    display:table; /* Give our .table divider a table display */
    width:100%;    /* Set its width to 100% to fill the screen */
}

.table-cell {
    padding:0 200px;  /* 200px left and right padding, 0 top and bottom */
    display:table-cell; /* Give our .table-cell divider a table-cell display */
    vertical-align:middle; /* Vertically align content to the middle */
}

.content { /* This is our content box */
    width:100px;
    height:100px;
    background:#f00;
    margin:0 auto;
}

JSFiddle Demo.

If you're unsure what I've done, here's a visualisation (using 50px padding rather than 200px):

Regular Size

Example of Result

Notice the effect of the padding when the result window is resized.

于 2013-10-03T08:07:30.440 回答
0

Use CSS media query's:

.centred {
    width: 400px; 
    margin: 0 auto;
}
@media only screen and (max-width : 600px) {
    .centred {
         margin-left: 200px; 
    }
}

Adjust the max-width to what you need.

于 2013-10-03T08:06:41.543 回答
0

我认为您应该能够使用媒体规则来做到这一点: https ://developer.mozilla.org/en-US/docs/Web/CSS/@media

.centred {
    width: 400px;
    margin: 0 auto;
}
@media screen and (max-width: 600px) {
    .centred {
        margin-left: 200px;
    }
}
于 2013-10-03T08:08:50.993 回答