仅当右边有元素时,如何在HTML元素中设置边距

时间:2019-06-15 14:08:11

标签: html css

我的问题是:如何在两个元素之间设置边距而不在较小的屏幕中对齐它们?

我正在创建一个HTML页面,其中有2个元素排成一行,如下所示:

enter image description here

我使它具有响应性,所以当我的屏幕较小时,元素将换行到另一行:

enter image description here

这是一个小玩意儿:https://jsfiddle.net/5ye2sc4b/1/

HTML:

<div class="container">
    <div class="header">Header</div>
    <div class="line">
        <div class="element element1">Element 1</div>
        <div class="element element2">Element 2</div>
    </div>
    <div class="footer">Footer</div>
</div>

CSS:

.container {
     display:flex;
     flex-direction: column;
     margin-top: 10px;
 }

.header, .footer {
  background-color: lightblue;
  padding: 5px;
  margin-bottom: 5px;
  margin-top: 5px;
}

.line {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.element {
  border: 1px solid gray;
  flex-grow: 1;
  height: 100px;
}

如果我在元素1中放置了右边距,它将在较大的屏幕中正确显示:

element1 { margin-right: 20px; }

enter image description here

但是它将在较小的屏幕上与标题对齐:

enter image description here

在上方的提琴手上,我放置了一些按钮来更改全局容器的大小,以模拟问题。

3 个答案:

答案 0 :(得分:1)

虽然我认为您的方法不是创建响应式布局的最佳方法,但您可能只希望在较小的屏幕上删除空白:

@media (max-width: 620px) {
margin-right: 0px
}

答案 1 :(得分:0)

我认为这更适合可以使用间隙的CSS网格:

.container {
  /*display: flex;
  flex-direction: column; not really useful in this  case*/
  margin-top: 10px;
}

.header,
.footer {
  background-color: lightblue;
  padding: 5px;
  margin-bottom: 5px;
  margin-top: 5px;
}

.line {
  display: grid;
  /* adjust the 200px to control when elements will wrap */
  grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
  /* margin only between columns */
  grid-column-gap:16px;
}

.element {
  border: 1px solid gray;
  height: 100px;
}
<div class="container">
  <div class="header">Header</div>
  <div class="line">
    <div class="element element1">Element 1</div>
    <div class="element element2">Element 2</div>
  </div>
  <div class="footer">Footer</div>
</div>

答案 2 :(得分:0)

您可以使用媒体查询来做到这一点:

请确保您的.line最初具有flex-flow: row nowrap;的简写代码。孩子的flex-direction: row; flex-wrap: nowrap;应该是50%

然后让媒体查询(flex-basis)完成其余工作。

只要屏幕低于900像素,就可以在媒体查询中应用CSS,如下所示:

@media

这将删除@media(max-width: 900px){ .line{ flex-flow: row wrap; } .element{ flex-basis: 100%; } .element1 { margin-right: 0px; } 中的边距,并将元素设置为100%element1以及flex basis上的flex wrap进行包装。

.line
.container {
     display:flex;
     flex-direction: column;
     margin-top: 10px;
 }

.header, .footer {
  background-color: lightblue;
  padding: 5px;
  margin-bottom: 5px;
  margin-top: 5px;
}

.line {
  display: flex;
  flex-flow: row nowrap;
}

.element {
  border: 1px solid gray;
  flex-grow: 1;
  height: 100px;
  flex-basis: 50%;
}

.element1 { margin-right: 20px; }


@media(max-width: 900px){
.line{
  flex-flow: row wrap;
}

.element{
flex-basis: 100%;
}
.element1 {
margin-right: 0px;

}