6 種CSS設定置中的方法

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   os   ar   for   

原文

Demos of each of the methods below by clicking here.

Horizontal centering with css is rather easy. When the element to be centered is an inline element we use text-align center on its parent. When the element is a block level element we give width and set the left and right margins to auto.

 

With text-align: center in mind, most people look first to vertical-align in order to center things vertically. 

Unfortunately vertical-align doesn’t apply to block-level elements like a paragraph inside a div, It applies to table cells and it works with some inline elements.

Line-Height Method

All we need to do is set a line-height on the element containing the text larger than its font-size.

<div id="parent">    <div id="child">Text here</div></div>
#child {    line-height: 200px;}

The above works in all browsers, however it will only work for a single line of text. If your text could wrap to a 2nd line you need to use a different method. The value of 200px above is arbitrary. You can use any value you want as long as its larger than the font-size that’s been set.

Centering an Image with Line-Height

What if the content you want centered is an image? Will this method work? The answer is yes with one additional line of css.

CSS Table Method

Above I mentioned that vertical-align applies to table cells which leads us to this method. We’ll display our elements as table and table cell and then use the vertical-align property to center the content.

Note: CSS tables are not the same as html tables.

 

 

6 種CSS設定置中的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.