首页 > 解决方案 > CSS - 将文本与 div 对齐

问题描述

我正在努力将文本与 div 对齐。

我目前有这个:

在此处输入图像描述

但我想实现这一点(我刚刚编辑了一个截图来告诉你我的意思):

在此处输入图像描述

我的代码如下所示:

HTML

<div class="regionHeader">
    <div class="regionArrow"></div>
    <h2>Some long header that should be aligned to the left next to the div with arrow</h2>
</div>

CSS

.regionHeader {
    border-bottom: 1px solid #ffd800;
    cursor: pointer;
}

.regionArrow {
    border-right: 4px solid #ffd800;
    border-bottom: 4px solid #ffd800;
    width: 13px;
    height: 13px;
    transform: rotate(45deg);
    float: left;
    margin-top: 11px;
    margin-right: 13px;
    margin-bottom: 0px;
    margin-left: 3px;
}

h2 {
    font-family: changa-regular;
    font-size: 2em;
}

我已经玩过显示和浮动,但它要么不起作用,要么我做错了。

标签: htmlasp.netcssalignment

解决方案


您可以简单地padding-left在标题上使用 a :

.regionHeader {
  border-bottom: 1px solid #ffd800;
  cursor: pointer;
}

.regionArrow {
  border-right: 4px solid #ffd800;
  border-bottom: 4px solid #ffd800;
  width: 12px;
  height: 13px;
  transform: rotate(45deg);
  float: left;
  margin-top: 11px 13px 0 3px;
}

h2 {
  font-size: 2em;
  padding-left: 1.2em; /* <- added */
}
<div class="regionHeader">
  <div class="regionArrow"></div>
  <h2>Some long header that should be aligned to the left next to the div with arrow</h2>
</div>

或者使用 flexbox 方法并删除float.

.regionHeader {
  border-bottom: 1px solid #ffd800;
  cursor: pointer;
  display: flex; /* <- added */
}

.regionArrow {
  border-right: 4px solid #ffd800;
  border-bottom: 4px solid #ffd800;
  width: 16px;
  height: 13px;
  transform: rotate(45deg);
  margin: 30px 15px;
}

h2 {
  font-family: changa-regular;
  font-size: 2em;
}
<div class="regionHeader">
  <div class="regionArrow"></div>
  <h2>Some long header that should be aligned to the left next to the div with arrow</h2>
</div>

浏览器对 flexbox的支持非常好。不要忘记添加适当的供应商前缀。


推荐阅读