Home  >  Article  >  Web Front-end  >  水平居中--行内元素、定宽块、不定宽块_html/css_WEB-ITnose

水平居中--行内元素、定宽块、不定宽块_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:38:511153browse

声明:来自http://www.imooc.com/learn/9 学习

行内元素

如果被设置元素为文本、图片等行内元素时,水平居中是通过给父元素设置 text-align:center 来实现的。

定宽块状元素

满足定宽和块状两个条件的元素是可以通过设置“左右margin”值为“auto”来实现居中的。

 1 margin:0 auto; 

不定宽块状元素

不定宽度的块状元素有三种方法居中(这三种方法目前使用的都比多):

  1. 加入 table 标签
  2. 设置 display;inline 方法
  3. 设置 position:relative 和 left:50%;

1.HTML代码:

 1 
2 3 4 11 12
5
    6
  • 1
  • 7
  • 2
  • 8
  • 3
  • 9
10
13

 

  CSS代码:

1 table{2     margin:0 auto;3 }4 ul{list-style:none;margin:0;padding:0;}5 li{float:left;display:inline;margin-right:8px;}

 

2.

html代码:

 

css代码:

 

这种方法相比第一种方法的优势是不用增加无语义标签,简化了标签的嵌套深度,但也存在着一些问题:它将块状元素的 display 类型改为 inline,变成了行内元素,所以少了一些功能,比如设定长度值。

3.HTML代码

通过给父元素设置 float,然后给父元素设置 position:relative 和 left:50%,子元素设置 position:relative 和 left:-50% 来实现水平居中。

代码如下:

 

css代码:

 

这种方法可以保留块状元素仍以 display:block 的形式显示,优点不添加无语议表标签,不增加嵌套深度,但它的缺点是设置了 position:relative,带来了一定的副作用。

这三种方法使用得都非常广泛,各有优缺点,具体选用哪种方法,可以视具体情况而定。

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn