你如何轻松地水平居中 <div>使用 CSS? [英] How do you easily horizontally center a <div> using CSS?
本文介绍了你如何轻松地水平居中 <div>使用 CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将 <div>
块元素在页面上水平居中,并将其设置为最小宽度.什么是最简单的方法来做到这一点?我希望
元素与页面的其余部分内联.我会试着画一个例子:
page text page text page text page text页面正文页面正文页面正文页面正文-------|div |-------页面正文页面正文页面正文页面正文页面正文页面正文页面正文页面正文
解决方案
在 非固定宽度 div 的情况下(即您不知道 div 将占用多少空间).
#wrapper {背景颜色:绿色;/* 用于可视化目的 */文本对齐:居中;}#yourdiv {背景颜色:红色;/* 用于可视化目的 */显示:内联块;}
<div id="yourdiv">你的文字</div>
请记住,#yourdiv
的宽度是动态的 -> 它会增长和缩小以容纳其中的文本.
您可以在 Caniuse
上检查浏览器兼容性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
解决方案
In the case of a non-fixed width div (i.e. you don't know how much space the div will occupy).
#wrapper {
background-color: green; /* for visualization purposes */
text-align: center;
}
#yourdiv {
background-color: red; /* for visualization purposes */
display: inline-block;
}
<div id="wrapper">
<div id="yourdiv">Your text</div>
</div>
Keep in mind that the width of #yourdiv
is dynamic -> it will grow and shrink to accommodate the text inside it.
You can check browser compatibility on Caniuse
这篇关于你如何轻松地水平居中 <div>使用 CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文