What is the best way to center an html element within its containing element?

心不动则不痛 提交于 2019-12-07 07:43:20

问题


Let's say you have the following chunk of code:

<div id="container">
  <someelement>This is any element.</someelement>
</div>

What's the best CSS I could use to horizontally center "someelement" within its containing div?


回答1:


if your <someelement> is an inline element (i.e defaults to display: inline) apply text-align: center to its container. If <someelement> is a block element set left and right margin to auto and remember to set a width (block elements default to take all available horizontal space unless a width is stated explicitly). You may have to use both methods if you want it to work in IE 5.5 and below too.




回答2:


JaredPar has the right idea, but here's a cleaner way to do what you're looking for ;)

#container {
    text-align: center;
}

#container someelement {
    margin: 0 auto;
    text-align: left;
}



回答3:


Try

<someelement style="margin-left:auto;margin-right:auto">This is any element</someelement>


来源:https://stackoverflow.com/questions/395484/what-is-the-best-way-to-center-an-html-element-within-its-containing-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!