如何在CSS的下一行中居中三个项目之一?



我是CSS的新手,现在我想了解它是如何工作的。我从CS50课程开始,我试着做那个课程的项目0,包括重现谷歌搜索前端。早些时候,我已经完成了这个项目,但现在我决定再做一次,并以flex-box为基础。我写了一个简短的代码,我想连接到谷歌搜索稍后。搜索栏、button1和button2项分别是:搜索栏、谷歌搜索按钮和"我感觉很幸运"。按钮。我现在试着将这些元素和按钮居中,使线条更低,但我真的不知道该怎么做。我尝试了flex-wrap: wrap和flex-basis,但这会导致元素改变行,但它们之间的间距是页面的一半,并且改变高度也不会做任何事情。有人知道如何使这项工作,而留在柔性箱?

.searcher {
display: flex;
background-color: gray;
color: white;
justify-content: center;
align-items: center;
flex-wrap: wrap;
height: 100%;
}
.searchbar {
margin: 1%;
}
.buttons {
margin: 1%;
}
<div class="searcher">
<div class="searchbar">
<p>searchbar</p>
</div>
<div class="buttons">
<p>button1</p>
</div>
<div class="buttons">
<p>button2</p>
</div>
</div>

如果更改HTML代码是一个选项,我有一个解决方案。

在两个按钮中加入div并将它们作为一个元素使用会使事情变得容易得多,并且可以让您按照自己的喜好重新组织它们。

.searcher {
display: flex;
background-color: gray;
color: white;
justify-content: center;
align-items: center;
flex-wrap: wrap;
height: 100%;
flex-direction: column;
}
.searchbar {
margin: 1%;
}
.buttons {
display: flex;
flex-direction: row;
}
.button {
margin: 1%;
}
<div class="searcher">
<div class="searchbar">
<p>searchbar</p>
</div>
<div class="buttons">
<div class="button">
<p>button1</p>
</div>
<div class="button">
<p>button2</p>
</div>
</div>
</div>

似乎你想要另一层沿着垂直轴的伸缩布局,你的布局的行将被放置。包含按钮的第二行将沿着水平轴布局为flexbox。

构建你的标记(为了演示目的右对齐按钮):

<html>
<head>
<style>
.searcher {
display:            flex;
flex-direction:     column;
background-color:   gray;
color:              white;
justify-content:    center;
align-items:        stretch;
flex-wrap:          wrap;
height:             100%;
}
.searchbar {
margin: 1%;
text-align: center;
}
.nav {
display:            flex;
flex-direction:     row;
flex-wrap:          nowrap;
justify-content:    right;

}
.buttons {
margin: 1%;
}
</style>
</head>
<body>
<div class="searcher">
<div class="searchbar">
<p>searchbar</p>
</div>
<div class="nav">
<div class="buttons">
<p>button1</p>
</div>
<div class="buttons">
<p>button2</p>
</div>
</div>
</div>
</body>
</html>

最新更新