我有一个类似的问题。设置
margin-left: auto;
margin-right: auto;
对于我来说,在内部div上操作起作用。
.content
为inline-block,只需设置容器的text-align: center
和内容的text-align: left
。使用margin:auto
将无法使inline-block元素居中。我试过这个,它有效果了
.element-container{
width:100%;
max-width: 700px;
margin: 0px auto;
}
.element{
width: 80%;
max-width: 700px;
height: auto;
margin-left: 10%;
}
display: flex
,因为它可以减少大量的CSS代码,如下所示:.main-container {
display:flex;
justify-content: center;
}
你可以将display更改为table
。
.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;
}
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;
}
dispaly: inline-block
来实现这个目标。你的答案在这里不起作用。 - Anton Belevdispaly: inline-block
来实现这一点。 - Anton Belev.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>
.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>