CSS various centering methods (GO)

Source: Internet
Author: User

水平居中的text-align:center 和 margin:0 auto

这两种方法都是用来水平居中的,前者是针对父元素进行设置而后者则是对子元素。他们起作用的首要条件是子元素必须没有被float影响,否则一切都是无用功。margin:0 auto 也可以被写成margin:0 auto 0 auto。不能理解的童鞋们可以自己去找找关于css缩写的内容。 垂直居中的line-height 什么?!margin在垂直居中里不起作用了?显然事情确实如此,我们仅有margin:0 auto的用法而没有auto 0的情况。至于line-height,他也是作用在父元素上,当他的值等于父元素的height值时 ,内部的文字就会自动的垂直居中了。此处好像仅仅只能是文字而已,遗憾。 万能的position大法 这个方法可以说真的是万能的。当你为一个元素无法居中而困扰的时候,可以果断的使用他,而且几乎没有后遗症,绝对是前端工程师们居家旅行必备的手段之一。 具体的做法很简单,首先给父元素写上positon:relative,这么做是为了给子元素打上position:absolute的时候不会被定位到外太空去。接下去,写上子元素的height和width,这个似乎是必须的 ,某些浏览器在解析的时候如果没有这2个值的话会出现意想不到的错位。接着就是整个方法的核心,给子元素再打上top:50%;left:50%以及margin-top:一半的height值的的负数; margin- left:一半的weight值的负数。整理一下之后,可能你会给你的子元素写上这样的css(当然,父元素也要先写上width和height) {width:100px;height:80px;position:absolute;top:50%;left:50%;margin-left:50px;margin-top:40px} 接下去就刷新页面吧,你的子元素已经是居中显示了。 使用这个方法的好处在于无论你是什么形式的内容都可以马上居中,而缺点就是必须对元素有确定的宽高值,否则的话可能就需要通过javascript来进行一些小计算了。

CSS various centering methods (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.