使用CSS的中心内容 [英] center content in div with CSS

查看:133
本文介绍了使用CSS的中心内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在div中水平和垂直居中内容。我会很高兴,如果有人给我小样本代码与css。

how to center content in div horizontally and vertically. i will be happy if someone give me small sample code with css.

推荐答案

这应该适合你的需要。这是一个CSS-2D转换技巧。我最近遇到了以下解决方案:

This should fit your needs. It is a CSS-2D-transition trick. I have recently come across the following solution:

HTML:

<h1 class="title">3 Boxes with different text-align settings.</h1>
<div class="blocks">
    <div class="block h-center">horizontally centered lorem ipsun dolor sit amet</div>
    <div class="block v-center"><span>vertically centered lorem ipsun dolor sit amet lorem ipsun dolor sit amet</span></div>
    <div class="block h-center v-center"><span>horizontally and vertically centered lorem ipsun dolor sit amet</span></div>
</div>

CSS

* {
    font-family: Arial;
    font-size: 14px;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
}

*:after, *:before {
    content: "";
    display: table;
}

*:after {
    clear: both;
}

.title {
    font-family: Georgia;
    font-size: 36px;
    line-height: 1.25;
    margin-top: 0;
}

.blocks {
    position: relative;
}

.block {
    position: relative;
    display: inline-block;
    float: left;
    width: 200px;
    height: 200px;
    font-weight: bold;
    color: #FFFFFF;
    margin-right: 10px;
    margin-bottom: 10px;
}

.block:first-child {
    background-color: green;
}

.block:nth-child(2) {
    background-color: red;
}

.block:nth-child(3) {
    background-color: blue;
}

.h-center {
    text-align: center;
}

.v-center span {
    position: absolute;
    left: 0;
    right: 0;
    top: 50%;
    transform: translate(0, -50%);
}

注意:这也适用于:after和:before -elements。

Note: This does also work with :after and :before pseudo-elements.

您也可以在这里阅读:css-tricks.com

You can also read here: css-tricks.com

您可以在这里测试: jsfiddle

这篇关于使用CSS的中心内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆