如何轻松横向居中< div>使用CSS? [英] How do you easily horizontally center a <div> using CSS?

查看:180
本文介绍了如何轻松横向居中< div>使用CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将页面上的< div> 块元素水平居中,并将其设置为最小宽度。最简单的方法是什么?我想要< div> 元素与我的页面的其余部分。我将尝试画一个例子:

I'm trying to horizontally center a <div> block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div> element to be inline with rest of my page. I'll try to draw an example:

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text


推荐答案

非固定宽度 div(即,你不知道

In the case of a non-fixed width div (ie. you don't know how much space the div will occupy).

<div id="wrapper" style="text-align: center">    
    <div id="yourdiv" style="display: inline-block;">You text</div>
</div>

在最新的chrome(19.0.1084.52),safari 5.1和firefox 12测试。I dunno about IE

Tested in the latest chrome (19.0.1084.52), safari 5.1 and firefox 12. I dunno about IE.

注意:请记住, #yourdiv 的宽度是动态的

NOTE: Keep in mind that the width of #yourdiv is dynamic -> it will grow and shrink to accommodate the text inside it.

注意:您可以在这里查看浏览器的相容性 - > http ://caniuse.com/inline-block

NOTE2: You can check browser compatibility here -> http://caniuse.com/inline-block

注意:根据一些用户,它似乎在最新的IE中工作

NOTE3: According to some users, it seems it works in latest IE

这篇关于如何轻松横向居中&lt; div&gt;使用CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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