对齐上方(相对于)div

时间:2018-05-04 05:05:58

标签: css flexbox

我有一些h2文本当前在移动视图中与左侧对齐,位于居中的div上方。我怎样才能在移动视图中将它相对于div左对齐(使用下面的CSS中提供的媒体查询)?

enter image description here

CodePen

相关HTML:

<section class="container-projects">
        <h2 class="portfolio-header">Featured Work</h2>
        <div class="project"> 

相关CSS:

    .portfolio-header {
      /* Puts header in its own row without removing from container with row flex direction (setting parent container to wrap also required) */
      width: 100%;
      text-align: left;
      color: #7d97ad;
    }

    .container-projects {
      display: flex;
      /* Parent container needs this for flex-item to take full width in row */
      flex-wrap: wrap;
      flex-direction: row;
      justify-content: space-between;
      margin: 2em 0;
    }

/* Special styling for screens up to 767px wide, inclusive (applies to landscape phones) */
@media screen and (max-width: 767px) {
  header, .container, footer {
    max-width: 100%;
  }

  /* Must specify max-width for img even though parent .container has the same declaration because max-width isn't inherited */
  .container img {
    max-width: 100%;
  }

  .project {
    /* Centers projects (aligned left otherwise) */
    margin: 0 auto;
  }

}

2 个答案:

答案 0 :(得分:0)

您可以为移动设备添加媒体查询

@media screen and (max-width: 600px) {
    .portfolio-header {
        width: 300px;
        margin: 10px auto;
    }
}

答案 1 :(得分:0)

https://codepen.io/anon/pen/OZjWwJ?editors=1100

略微修改HTML

<section class="portfolio">
  <h2 class="portfolio-header">Featured Work</h2>
  <div class="container-projects">
    <div class="project">
      <img class="project-image" src="https://image.ibb.co/hv4c8n/santorini_small.jpg" alt="View from island of Santorini on a sunny day">
      <h3>Project No. 1</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
    <div class="project">
      <img class="project-image" src="https://image.ibb.co/c9sKM7/coast_small.jpg" alt="Distant view of a rugged island with a sailboat nearby">
      <h3>Project No. 2</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
    <div class="project">
      <img class="project-image" src="https://image.ibb.co/eO9oES/mediterranean_small.jpg" alt="Bird's eye view of a rocky beach with clear turquoise waters">
      <h3>Project No. 3</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </div>
</section>

和CSS

.portfolio {
  margin: 0 auto;
  width: 100%;
}

@media screen and (max-width: 992px) {
  .portfolio {
    width: 90%;
  }
}

这样,您将h2和项目图像包装在一个容器中,这使得在屏幕上管理其边距更合乎逻辑。 margin: 0 auto将容器对齐在屏幕中央,这在所有屏幕宽度上都是可取的。

992px媒体查询来自Bootstrap 4的标准化网格系统:https://getbootstrap.com/docs/4.0/layout/grid/#grid-options