首页 > 解决方案 > 如何水平对齐伪元素与元素及其容器

问题描述

我最近经历了一些 CSS 练习。假设我有一个日历 Web 应用程序的以下 HTML/CSS 代码,您可以在我的Codepen中看到。我需要的是让“.day_body”元素和“+”伪元素以及它的白色圆圈容器水平对齐。此外,我需要将“+”放在白色圆圈的中心。不幸的是,现在编辑 HTML 或使用 flexbox 不是一个选项。关于如何做到这一点的任何想法?

<div class="calendar_plan">
 <div class="day_title">Today</div>
 <div class="day_body">19 May 2020</div>
 <div class="day_add">
  <span class="plus_sign"></span>
 </div>
<div>

.calendar_plan {
  background-color: teal;
  color: #fff;
  margin-top: 2rem;
  margin-bottom: 4rem;
  padding: 3rem;
  clear: both;
  overflow: hidden;
}
.day_title {
  font-size: 2.2em;
  font-weight: 800;
}
.day_body {
  font-size: 2em;
  float: left;
}
.day_add {
  margin-left: 20px;
  float: left;
}
.day_add:after {
  display: block;
  width: 4rem;
  height: 4rem;
  content: "\002B";
  font-size: 4rem;
  color: #999;
  background-color: #fff;
  border-radius: 50%;
  line-height: 4rem;
}
.day_add:hover:after {
  cursor: pointer;
}

标签: htmlcssfrontend

解决方案


就像评论中已经提到的那样,添加text-align: center;.day-add有助于对齐加号。

要将日期与圆圈水平对齐,您可以将 的 line-height 增加到圆圈 line-height 的.day_body一半 ( 4em): line-height: 2em;。尽管如此,这会使日期稍微“向下”。可以吗?

或者,您可以使用圆的绝对定位。

.calendar_plan {
  background-color: teal;
  color: #fff;
  margin-top: 2rem;
  margin-bottom: 4rem;
  padding: 3rem;
  clear: both;
  overflow: hidden;
}

.day_title {
  font-size: 2.2em;
  font-weight: 800;
}

.day_body {
  font-size: 2em;
  float: left;
  line-height: 2em;
}

.day_add {
  margin-left: 20px;
  float: left;
  text-align: center;
}

.day_add:after {
  display: block;
  width: 4rem;
  height: 4rem;
  content: "\002B";
  font-size: 4rem;
  color: #999;
  background-color: #fff;
  border-radius: 50%;
  line-height: 4rem;
}

.day_add:hover:after {
  cursor: pointer;
}
<div class="calendar_plan">
  <div class="day_title">Today</div>
  <div class="day_body">19 May 2020</div>
  <div class="day_add">
    <span class="plus_sign"></span>
  </div>
  <div>


推荐阅读