[英]CSS: Won't center div with max-width
我有一個類似的問題。 設置
margin-left: auto;
margin-right: auto;
在內部div為我工作。
如果您需要.content
為內聯塊 ,只需設置容器text-align: center
和內容text-align: left
。 您將無法使用margin: auto
來居中嵌入塊元素。
我試過這個並且它有效
.element-container{
width:100%;
max-width: 700px;
margin: 0px auto;
}
.element{
width: 80%;
max-width: 700px;
height: auto;
margin-left: 10%;
}
您可以將顯示更改為table
。 http://jsfiddle.net/4GMNf/14/
.main-container {
max-width: 800px;
margin: auto;
position: relative;
background-color: red;
}
.content {
margin: auto;
max-width: 600px;
height: 300px;
background-color: gray;
display: table;
}
table
{
width: 200px;
}
刪除display: inline-block;
來自.content
CSS類
試試這個
CSS
.main-container {
max-width: 800px;
margin: auto;
position: relative;
background-color: red;
}
.content {
margin: auto;
max-width: 600px;
height: 300px;
background-color: gray;
}
table {
width: 200px;
}
實際上,一個內聯塊元素沒有采用寬度為父,它仍然是內容寬度,因為內聯塊元素在塊和非塊或內聯之間的中間位置。 所以,當你說這個元素是內聯塊時,然后談談父文本對齊中心。
這里的代碼:
ANS-1:
.main-container { max-width: 800px; margin: auto; position: relative; background-color: red; text-align: center; } .content { margin: auto; max-width: 600px; height: 300px; background-color: gray; display: inline-block; text-align:left; } table { width: 200px; }
<div class="main-container"> <div class="content"> <table> <thead> <tr> <h1>Name</h1> </tr> </thead> <tbody> <tr> <input type="text" Text="" id="txt"> </tr> </tbody> </table> </div> </div>
答案2:
.main-container { max-width: 800px; margin: auto; position: relative; background-color: red; } .content { margin: auto; max-width: 400px; height: 300px; background-color: gray; } table { width: 200px; }
<div class="main-container"> <div class="content"> <table> <thead> <tr> <h1>Name</h1> </tr> </thead> <tbody> <tr> <input type="text" Text="" id="txt"> </tr> </tbody> </table> </div> </div>
您可以使用display: flex
,因為它可以減少很多CSS代碼,如下所示;
.main-container {
display:flex;
justify-content: center;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.