CSS Tricks

CSS Tricks

一些CSS的小技巧

1.如何准确的居中?
参考Quick CSS Trick: How To Center an Object Exactly In The Center

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
}

2.铺满背景的图片
参考Perfect Full Page Background Image,有多种方式

例如,使用background-size: cover

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

3.display:block/inline-block时的居中

参考How to center things - display:block/inline-block

margin:0 auto;一般用于块级元素的居中
而对于display: inline,居中的唯一方式是:在父级元素上指定text-align: center
display: inline-block可以一个接一个的显示元素,也可以利用display: block的一些有用的东西,例如,最常用的就是HEIGHT

4.div中inline-block元素的垂直居中
参考Align inline-blocks with vertical-align,多种方式

如使用伪类:

<h3>With an added pseudo element it's possible</h3>
<div class="block2">
  <div class="inner">Inline-Block</div>
  <div class="inner">Inline-Block</div>
</div>

/* With an added fake (pseudo) element it works. IMPORTANT: There must be no spaces between the elements in the source, else it doesn't work! */
.block2 {
  background: orange;
  height: 80px;
}
.inner {
  display: inline-block;
  vertical-align: middle;
  background: yellow;
  padding: 3px 5px;
}

/* Fake (pseudo) element, that enables vertical-align */
.block2:before {
  content: "";
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

效果

5.div中一个div垂直对齐
参考Vertically centering a div inside another div

HTML

<div class="cn"><div class="inner">your content</div></div>

a.父元素使用table-cell,子元素使用inline-block

.cn {
  display: table-cell;
  width: 500px;
  height: 500px;
  vertical-align: middle;
  text-align: center;
}

.inner {
  display: inline-block;
  width: 200px; height: 200px;
}

效果如下:

实际效果

b.更现代的方式,使用transform

    .cn {
        position: relative;
        width: 500px;
        height: 500px;
        border: 1px solid red;
    }

    .inner {
        position: absolute;
        top: 50%; left: 50%;
        transform: translate(-50%,-50%);
        width: 200px;
        height: 200px;
        border: 1px solid blue;
    }

c.使用flexbox

.cn {
  display: flex;
  justify-content: center;
  align-items: center; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值