我使用mobile-first方法创建了一个响应式四列布局。最小的屏幕显示1列,较大的屏幕显示2列,最大的屏幕显示4列。
到目前为止,它似乎是有效的,但我想让你看看我的代码,告诉我我的方法是否有什么问题。我很感激你的意见。
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FlexBox Test</title>
<style>
:root {
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit;
}
/* mobile phone */
.flex-container {
display: flex;
flex-wrap: wrap;
max-width: 1400px;
margin: 0 auto;
border: 1px solid red;
padding: 1em;
}
.flex-item-1 {
background: indianred;
}
.flex-item-2 {
background: blue;
}
.flex-item-3 {
background: tomato;
}
.flex-item-4 {
background: coral;
}
.flex-item {
flex: 100%;
height: 100px;
}
/* tablet */
@media screen and (min-width: 640px) {
.flex-item {
flex: calc(50% - 1em);
}
.flex-item:nth-child(2n) {
margin-left: 1em;
}
}
/* desktop */
@media screen and (min-width: 960px) {
.flex-item {
flex: calc(25% - 1em);
}
.flex-container > * + * {
margin-left: 1em;
}
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item flex-item-1">
1
</div>
<div class="flex-item flex-item-2">
2
</div>
<div class="flex-item flex-item-3">
3
</div>
<div class="flex-item flex-item-4">
4
</div>
</div>
</body>
</html>
最佳答案
如果你想从css中删除calc,你可以这样做。
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FlexBox Test</title>
<style>
:root {
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit;
}
/* mobile phone */
.flex-container {
display: flex;
flex-wrap: wrap;
max-width: 1400px;
margin: 0 auto;
border: 1px solid red;
padding: 1em;
}
.flex-item-1 {
background: indianred;
}
.flex-item-2 {
background: blue;
}
.flex-item-3 {
background: tomato;
}
.flex-item-4 {
background: coral;
}
.flex-item {
flex: 100%;
height: 100px;
}
/* tablet */
@media screen and (min-width: 675px) and (max-width: 960px) {
.flex-item {
flex: 1 0 19em;
}
.flex-item:nth-child(2n) {
margin-left: 1em;
}
}
/* desktop */
@media screen and (min-width: 960px) {
.flex-item {
flex: 1 0;
}
.flex-container > * + * {
margin-left: 1em;
}
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item flex-item-1">
1
</div>
<div class="flex-item flex-item-2">
2
</div>
<div class="flex-item flex-item-3">
3
</div>
<div class="flex-item flex-item-4">
4
</div>
</div>
</body>
</html>
不过,要保持初始示例中的边距,我必须更改tablet屏幕的
@media screen and (min-width: 675px) and (max-width: 960px)
。如果不是,则在第一行显示特定浏览器宽度的三个块(与您所需的行为不同)。你觉得怎么样?
关于html - 自适应四列布局Flexbox需要的意见,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54670754/