簡體   English   中英

不能使用text-align:center來居中div

[英]Cannot center inner div with text-align: center

我以前認為下面的兩個代碼塊都會正確地居中div(當然,舊版瀏覽器存在一些問題)。 第一種方法使用text-align: center而第二種方法使用auto左右邊距。 但是,下面的第一個代碼塊並不像我期望的那樣使內部div居中。 有什么想法嗎?

 <div style="text-align: center; background-color: red;"> <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue">Not working</div> </div> 

以下代碼確實使div居中:

 <div style="background-color: red;"> <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; margin-right: auto">Works</div> </div> 

這是我的JSFiddle

它是一個塊級元素,它的位置不受text-align屬性的影響。 如果將其設置為display-inline ,它將起作用。

<div style="text-align: center; background-color: red;">
    <div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; display: inline-block;">It will work now</div>
</div>

中心的div有margin-left: automargin-right: auto ,不工作的div缺少任何邊距。

看這個DEMO

在頂部框中,我添加了: margin: 0 auto ,這是簡寫: margin-top: 0; margin-bottom: 0; margin-left: auto; margin-right: auto; margin-top: 0; margin-bottom: 0; margin-left: auto; margin-right: auto;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM