首页 > 解决方案 > 将 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;
}

提前致谢!

标签: htmlcss

解决方案


这是一个使用空 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>


推荐阅读