html - 将 div 对齐到容器的右端,将标题对齐到容器的中心
问题描述
与header
中心对齐,与checkbox-div
下一行对齐,我应该使用什么 css 将checbox-div
右端与标题对齐在同一行!
这是示例代码!
<div class="header-wrapper">
<h2 class="header">Header</h2>
<div class="checkbox-div">
<input type="checkbox" class="checkbox" value="Some Value" id="checkbox">
<label for="sub-folder-checkbox">Some Name</label>
</div>
</div>
目前使用的css是,
.header {
text-align: center;
}
提前致谢!
解决方案
这是一个使用空 div 作为“spacer”元素的 flexbox 示例。我在代码中留下了注释,解释了它们下面的代码的作用。我为一些元素添加了颜色,这样你就可以看到它们发生了什么。
.header {
text-align: center;
}
.header-wrapper {
display: flex;
/*We want 1 row and we dont want items to wrap into other rows*/
flex-flow: row nowrap;
width: 100%;
background-color: green;
/*Positions elements to the start, end and whatever is between while keeping some space between them */
justify-content: space-between;
/*You can add this if you also want to horizontally align items*/
align-items: center;
}
/*gives all divs (the spacer and the checbox-div) inside of the header-wrapper the same size and leaves the rest of space for the header, with this the header is centered and looks better*/
.header-wrapper div {
width: 33%;
}
.checkbox-div {
background-color: red;
}
<div class="header-wrapper">
<!--Add an empty container to fill in the place on the left-->
<div class="empty-div"></div>
<h2 class="header">Header</h2>
<div class="checkbox-div">
<input type="checkbox" class="checkbox" value="Some Value" id="checkbox">
<label for="sub-folder-checkbox">Some Name</label>
</div>
</div>
这是具有不同解决方案的第二个片段,代码被注释以再次解释。
.header-wrapper {
/*make the container a flex item and make it relative*/
display: flex;
position: relative;
width: 100%;
background-color: green;
/*Center the header*/
justify-content: center;
/*if horizontal centering is required add this*/
align-items: center;
}
.checkbox-div {
/*give the div an absolute position inside the parent container all the way on the right*/
position: absolute;
right: 0;
background-color: red;
}
<div class="header-wrapper">
<h2 class="header">Header</h2>
<div class="checkbox-div">
<input type="checkbox" class="checkbox" value="Some Value" id="checkbox">
<label for="sub-folder-checkbox">Some Name</label>
</div>
</div>
推荐阅读
- mysql - 错误 1045 (28000):Linux 上用户 'rumba'@'localhost' 的访问被拒绝(使用密码:NO)
- excel - 如何使用 VBA 宏自动提取保存的 csv 文件并将其放入现有工作表位置
- python - 谷歌 API OAuth 2 和 Django
- android - 将布局重力更改为中心将 TextView 隐藏在选项卡后面
- python - HTML子页面更改而不更改url
- reactjs - 来自深度嵌套的孩子时获取空白页
- python - 无法加载图片,图片 url 自动更改 url
- pandas - 没有表格环境的熊猫 to_latex?
- javascript - 如何以 reactjsonschema 形式更新 schema 和 uiSchema?
- java - 如何在 java 中创建带有对象类的数组 [家庭作业]