使用 Margin Auto & Flex 对齐文本



我有三个部分,根据用户输入,其中两个部分可能有不同大小的图像,也可能没有。在这两个部分是文本,即使图像的高度不相同,我也希望对齐。我已经将显示flex的部分以及文本的父元素和我的文本分配到页边空白:auto。据我所知,这应该有效。为了实现这一目标,我缺少什么?如有任何指导,我们将不胜感激。

section.wraps-section {
text-align: center;
padding: $section-padding-y*5 $section-padding-x $section-padding-y*3;
header {
padding-bottom: $base-spacing;
h2 {
color: $white;
mark {
color: $primary-color;
}
}
}
.section-body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 100px;
@include lg-up {
flex-direction: row;
}
.block {
&.content {
.block-body {
display: flex;
flex-direction: column;
}
p {
color: $white;
font-family: $tertiary-font-stack;
font-size: 30px;
margin-top: auto;
}
}
&.svg {
width: 100px;
svg {
width: 100%;
}
}
}
}
}
<section class="wraps-section" style="<?= $bg_style ?>">
<header>
<h2><?= $section_title ?></h2>
</header>
<div class="section-body">
<div class="block content">
<div class="block-body">
<img src="<?= $before_image_url ?>">
<p><?= $before_title ?></p>
</div>
</div>
<div class="block svg">
<?php Assetsrender_svg('wrap-arrow'); ?>
</div>
<div class="block content">
<div class="block-body">
<img src="<?= $after_image_url ?>">
<p><?= $after_title ?></p>
</div>
</div>
</div>
<div class="section-footer">
<?php if ($cta_text && $cta_url): ?>
<a href="<?= $cta_url ?>" class="button"><?= $cta_text ?></a>
<?php endif; ?>
</div>
</section>

您已接近目标,但有两个问题需要解决:

1.align-items: center

您已将align-items: center添加到.section-body中。这意味着孩子们将居中对齐,不会占据.section-body身高的100%

2..block.content

.block.content不占其父对象高度的100%。要解决这个问题,您可以简单地添加规则display: flex;

下面是一个示例,其中包含代码的简化版本和编译的css:

section.wraps-section {
text-align: center;
}
section.wraps-section .section-body {
display: flex;
gap: 100px;
flex-direction: row;
}
section.wraps-section .section-body .block.content {
display: flex;
}
section.wraps-section .section-body .block.content .block-body {
display: flex;
flex-direction: column;
}
section.wraps-section .section-body .block.content p {
margin-top: auto;
}
<section class="wraps-section">
<div class="section-body">
<div class="block content">
<div class="block-body">
<img src="http://placehold.jp/120x150.png">
<p>
Lorem ipsum dolor sit amet
</p>
</div>
</div>
<div class="block content">
<div class="block-body">
<img src="http://placehold.jp/150x150.png">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit.
</p>
</div>
</div>
</div>
</section>

未编译的scs:

section.wraps-section {
text-align: center;

.section-body {
display: flex;
// align-items: center will center the items, meaning they won't take the full height of their parent    
// align-items: center;
gap: 100px;
flex-direction: row;
.block {
&.content {
// By adding display: flex, you make .content the full height of it's parent
display: flex;

.block-body {
display: flex;
flex-direction: column;
}
p {
margin-top: auto;
}
}
}
}
}

最新更新