是否有一种“css”方式可以使居中的 div 表现得好像它有一个最小的左边距?我希望一个居中的 div 以页面为中心,除非该页面的宽度小于某个值。类似于以下内容:
.centred { width: 400px; margin: 0 auto; min-margin-left: 200px; }
我知道 min-margin-left 不存在,但我怎么能做到这一点?下面是图片中的示例。认为灰色边框是浏览器,蓝色框是我的“中心”div。
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
.
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;
}
If you're unsure what I've done, here's a visualisation (using 50px padding
rather than 200px):
Regular Size
Notice the effect of the padding when the result window is resized.
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.
我认为您应该能够使用媒体规则来做到这一点: 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;
}
}