首页 > 解决方案 > 如何将元素与容器的顶部和底部对齐?

问题描述

我可以使用 flexbox 将所有元素与容器底部对齐。但我不知道如何将这些元素之一与容器顶部对齐。例如,在此示例中,我无法将文本放到容器的顶部。

jQuery(document).ready(function($) {
      $('.slider').slick({
        speed: 500,
        slidesToShow: 3
    });
});
html, body {
  background: #102131;
  color: white;
}

.container {
  position: relative;
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
}


.slick-slider {
  background: #3a8999;
  font-size: 20px;
  text-align: center;
  width: 90%
}
<link href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick-theme.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
<div class="container">

  <div>
    <h1>This text should go to the top </h1>
  </div>

  <div class="slider" data-slick="{'arrows': true}">
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
  </div>
	
	<div>
		<h1>This text should stay at the bottom</h1>
	</div>
	
</div>

标签: htmlcssflexbox

解决方案


在 flex 容器中时,您可以使用margin: auto样式将项目推送到容器的一侧或另一侧。在这种情况下,如果您希望顶部元素紧贴容器顶部,请margin-bottom: auto在顶部元素上使用。

这是您添加的代码段:

jQuery(document).ready(function($) {
      $('.slider').slick({
        speed: 500,
        slidesToShow: 3
    });
});
html, body {
  background: #102131;
  color: white;
}

.container {
  position: relative;
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
}

.hug-top {
  margin-bottom: auto;
}

.slick-slider {
  background: #3a8999;
  font-size: 20px;
  text-align: center;
  width: 90%
}
<link href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick-theme.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js"></script>
<div class="container">

  <div class="hug-top">
    <h1>This text should go to the top </h1>
  </div>

  <div class="slider" data-slick="{'arrows': true}">
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
    <div>Slider stays directly above text below</div>
  </div>
	
	<div>
		<h1>This text should stay at the bottom</h1>
	</div>
	
</div>


推荐阅读