网站布局分为行和列-对齐问题

时间:2019-05-27 09:11:11

标签: css

我想创建一个布局,将页面分成行和模块。

行只是整个宽度的flex div,其中包含我称为模块的其他元素,如下图所示:

enter image description here

您还可以看到,当我有一栏时,内容居中-但这不是规则。但是我希望能够使内容居中(可能是任何东西)。

当我有两列时,左一列应右对齐,而右一列应左对齐。处于“中心”位置。

问题是,当我在使用CSS沙箱时,看起来像我想要的东西。但是,当我将其移到我的项目中时,它不起作用。主要是左列未正确对齐。怎么了?

哦,当然,所有的东西都应该响应:)

:root {
--default-padding: 20px;
--default-margin: 20px;
--double-margin: calc(var(--default-margin) * 2);
--double-padding: calc(var(--default-padding) * 2);
}

.row {
    display: flex; 
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: top;
    width: 100%
  }

.row > div {
   flex-grow: 1;
   width: 0px;
   min-width: 200px; /* it makes flex responsive */
}

.row > div:first-child > * {
   margin-left: auto;
   margin-right: var(--default-margin);
   text-align: right;
}

.row > div:last-child > * {
   margin-left: var(--default-margin);
}

img {
    max-width: 100%;
    height: auto; /* responsive image */
}
<div class="row">
    <div>
        <h1 style="text-align: center">Centered content</h1>
    </div>
</div>

<div class="row">
    <div>
        <img src="img.jpg" id="main_img"/>
    </div>

    <div>
      <p>
        <h1>Some header</h1>
        <ul>
          <li>list item</li>
          <li>list item</li>
        </ul>
      </p>
      <button class="cta module-right">ZAMÓW TERAZ</button>
    </div>
</div>

那么,这段代码怎么了? (这是我在CSS中的起点,我主要是台式机和后端程序员)

1 个答案:

答案 0 :(得分:0)

实现此目标的最佳方法是使用display: flex;。如果您不熟悉它,建议您从这里https://css-tricks.com/snippets/css/a-guide-to-flexbox/了解它,因为它会使您容易得多。我已经完成了您想使用flex实现的示例代码。希望这会有所帮助

HTML

<div class="d-flex flex-row justify-content-center">
  <h1>Centered content</h1>
</div>

<div class="d-flex flex-row justify-content-center">

  <div class="img-box">
    <img src="https://via.placeholder.com/150" />
  </div>

  <div class="flex-column">
    <div>
      <h1 class="no-margin">Some header</h1>
      <ul>
        <li>list item</li>
        <li>list item</li>
      </ul>
    </div>
    <div>
      <button>ZAMÓW TERAZ</button>
    </div>
  </div>

</div>

CSS

.d-flex {
  display: flex;
}

.flex-row {
  flex-direction: row;
}

.flex-column {
  flex-direction: column;
}

.justify-content-center {
  justify-content: center;
}

.img-box {
  margin-right: 1rem;
}

.no-margin {
  margin: 0;
}

JS小提琴链接:https://jsfiddle.net/SJ_KIllshot/gh6d5uzy/1/