【发布时间】:2019-02-15 18:00:41
【问题描述】:
我有 3 个弹性项目(每个项目都是一个 div)。每个弹性项目包含一个图像、2 个段落标签和一个 div(用于按钮)。我正在尝试将每个弹性项目中的每个按钮水平居中。
我尝试在 flex 容器中设置 justify-content:center; 但这不起作用。 (我不认为这是我想要的,因为我只希望 div 水平居中)我还尝试将 margin: 0 auto; 设置为按钮。这些似乎都不起作用。目前,每个 flex 项目的宽度为 33%,因此我将内部 div 设置为具有 position: absolute; 和 left: 16.5%;(容器宽度的一半)。但这看起来不对。这是我得到的最接近的。关于如何使它看起来更好的任何想法?
HTML:
<section class="overview-section">
<h2>Overview</h2>
<div class="row">
<div class="box">
<img src="https://images.unsplash.com/photo-1550129460-d47c2040f9df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=282&q=80">
<p class="under-text">TITLE GOES HERE</p>
<p class="txt">adsf adsf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf </p>
<div class="btn">Learn more</div>
</div>
<div class="box">
<img src="https://images.unsplash.com/photo-1550129460-d47c2040f9df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=282&q=80">
<p class="under-text">TITLE GOES HERE</p>
<p class="txt">adsf adsf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
</p>
<div class="btn">Learn More</div>
</div>
<div class="box">
<img src="https://images.unsplash.com/photo-1550129460-d47c2040f9df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=282&q=80">
<p class="under-text">TITLE GOES HERE</p>
<p class="txt">adsf adsf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf
</p>
<div class="btn">Learn more</div>
</div>
</div>
</section>
CSS:
@import url("https://fonts.googleapis.com/css?family=Oswald:300,400,500");
@import url("https://fonts.googleapis.com/css?family=Lato:400,700");
@import url("https://fonts.googleapis.com/css?family=Staatliches");
.row {
display: flex;
margin: 0 -50px;
}
.box {
position: relative; /* button will be positioned relative to this container */
border: 2px solid blue;
width: 33%;
height: 450px;
margin: 0 50px;
}
.box img {
width: 100%;
height: 250px;
}
.under-text {
font-family: "Staatliches", cursive;
color: red;
text-align: center;
}
.txt {
padding-left: 20px;
}
.btn {
position: absolute;
left: 16.5%;
bottom: 0;
background-color: #4caf50;
border: none;
color: black;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
background-color: white;
color: black;
border: 2px solid #4caf50;
}
Codepen:https://codepen.io/anon/pen/rPqgVm
预期结果:弹性项目中的每个 div 都应该水平居中。
【问题讨论】:
-
你的
btn不是一个flex item(flex child),你的box是,所以如果你让box显示flex,带有flex方向列,然后设置align-items: center他们会的。并删除btn上的绝对位置。更新代码笔:codepen.io/anon/pen/QYJLKy?editors=1100