【问题标题】:Vertical and Horizontal alignment of text with CSS [duplicate]使用CSS的文本垂直和水平对齐[重复]
【发布时间】:2014-04-19 03:01:30
【问题描述】:

我正在尝试在 div 框内(带有背景颜色)水平和垂直对齐文本,但我无法做到。

我在网上搜索过,margin: autotext-align: center 没有做这项工作。

有什么建议吗?

检查FIDDLE

HTML

<div id="services"><div class="holder container clearfix">
<div class="bgtop"><span class="top">Corte cabelo + Afiar</span></div>
<div class="bgprice"><span class="price">10€</span></div>
</div></div>

CSS

#services .holder .bgtop{
    background-color: #27ae60;
    height:50px;
    width:200px;
    z-index: 1;
}
#services .holder .bgprice{
    height:50px;
    width:90px;
    background-color: #272727;
    z-index: 1;
}
#services .holder span.top{
    color: white;
    font-style: italic;
    font-weight: bold;
    font-size: 1.000em;
    z-index: 2;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;  
    margin: auto;
    text-align: center;
}
#services .holder span.price{
    color: white;
    font-style: italic;
    font-weight: bold;
    font-size: 1.500em;
    z-index: 2;
    text-align: center;
}

【问题讨论】:

    标签: css html alignment center


    【解决方案1】:

    这是用于垂直/水平居中的常用方法。

    BASIC EXAMPLE HERE

    div {
        background: red;
        width:100px;
        height: 100px;
        display:table;
    }
    div > span {
        display:table-cell;
        vertical-align:middle;
        text-align:center;
    }
    

    基本上,父元素的显示更改为table。添加一个子元素,在本例中为 span 元素来包装文本。 span 应该具有属性 display:table-cell/vertical-align:middle 用于垂直居中。那么text-align:center 只是为了水平居中。

    这里是an example,使用您的样式。

    【讨论】:

    • 我已经看到了这种方法并且我已经尝试过,但它不适合我
    • @uniqezor 你看过这个例子吗?它有效.. jsfiddle.net/SyQe7
    【解决方案2】:

    您可以仅将您的 CSS 更改为此(不更改 HTML):

    div{
      background: red;
      bottom: 0;
      height: 100px;
      left: 0;
      margin: auto;
      position: absolute;
      top: 0;
      right: 0;
      width: 100px;
      text-align: center;
      line-height: 100px;
    }
    

    text-align 是不言自明的。 line-height 通过将单行的高度与 div 的高度匹配来强制文本居中。您每次都必须根据自己的需要进行调整。

    JSFiddle

    【讨论】:

    • 您可以按照我在小提琴示例中的方式进行编辑吗?我没有做对,所以它没有效果......
    • 当然可以,但是如果元素的高度是动态的呢?
    • 事情变得有点困难。如果您可以更改 HTML,那么执行其他答案中显示的内容是有意义的(例如 display: table-cell;)。您还可以使用 javascript 根据其容器设置行高。还有其他技术可以在特定浏览器中使用,但不能全面发挥作用。您必须找到所有的 CSS hack 才能使其正常工作。
    【解决方案3】:

    有不同的方法。这是一个:

    HTML:

    <div>
        <span>magix!</span>
    </div>
    

    CSS:

    div {
        text-align:center;
        display:table;
    }
    span { 
        display: table-cell;
        vertical-align:middle;
    }
    

    Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2011-07-22
      • 2020-04-02
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 2012-05-17
      相关资源
      最近更新 更多