【问题标题】:How to center content using :before in CSS如何在 CSS 中使用 :before 使内容居中
【发布时间】:2018-11-30 03:59:26
【问题描述】:

我有以下css代码:

它会在图像上产生悬停。

悬停效果是一个蓝色封面和一个从左侧滑入的白色箭头。

像这样:

悬停:

悬停:

"\f04b" 是白色箭头。如何将图标居中在蓝色框中?我尝试向

添加填充

sidebar-article-thumb:before, .sidebar-best-thumb:before

但它为整个蓝色叠加层添加了填充,而不是里面的白色图标。

如何让图标在蓝色框内居中?

.sidebar-article-thumb img,
.sidebar-best-thumb img {
  border: 1px solid #021a40;
  position: relative;
  max-width: none;
  height: 100%;
  width: auto;
  left: 50%;
  -moz-transform: translateX(-50%);
  -ms-transform: translateX(-50%);
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

.sidebar-article-thumb:before,
.sidebar-best-thumb:before {
  content: "\f04b";
  font-family: FontAwesome;
  font-size: 40px;
  color: #fff;
  position: absolute;
  top: 0;
  left: -100%;
  height: 100%;
  width: 100%;
  background: #00ade6;
  z-index: 1;
  -webkit-transition: all 0.3s ease;
  -moz-transition: all 0.3s ease;
  -o-transition: all 0.3s ease;
  transition: all 0.3s ease;
}

我发现了以下内容: :before, :after and padding

这似乎相关,但无法弄清楚如何将其应用于上述 css。

【问题讨论】:

  • 也分享你的html sn-p。
  • 尝试用你的代码做在线演示。

标签: html css


【解决方案1】:

Line-height 可以,\f04b 是一个字符。

line-height: 50%;

line-height: 100px;

【讨论】:

    【解决方案2】:

    在容器中使用position: relative

    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    

    在伪元素 (:before) 中使字符居中。

    示例:

    .container {
    	position: relative;
    
    	/* Demo */
    	width: 300px;
    	height: 300px;
    	border: 1px solid #000;
    }
    
    .container:before {
      content: '';
    	position: absolute;
    	top: 50%;
    	left: 50%;
    	transform: translate(-50%,-50%);
    
    	/* Demo */
    	width: 30px;
    	height: 30px;
    	border: 1px solid #000;
    }
    <div class="container"></div>

    【讨论】:

      【解决方案3】:

      尝试使用vertical-align: middle;

      【讨论】:

        【解决方案4】:

        在容器上使用 flexbox 会产生奇迹。

        .container {
            align-items: center;
            display: flex;
            justify-content: center;
        }
        

        JSFiddle

        (我只是生成了自己的箭头,而不是使用font-awesome,但原理还是一样的)

        【讨论】:

        • 我仍然无法评论其他帖子(今天才开始)。使用绝对位置要求您知道元素的高度和宽度,并从 50% 中减去。垂直对齐当然只会垂直居中。使用 flexbox 是垂直和水平居中的最佳和最简单的方法。
        • 你根本不需要知道宽高,只要使用transform: translate(-50%,-50%); (这与 margin-top: - ( height / 2 ) 和 margin.left: (width / 2 ) 的工作方式相同。
        猜你喜欢
        • 2012-10-16
        • 2011-05-30
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 2011-10-11
        • 2012-02-28
        • 2013-08-03
        • 1970-01-01
        相关资源
        最近更新 更多