我在父元素内有inline-block
个元素的列表。我不会将父元素居中,同时将子元素保持在左侧。
<body>
<style>
.container {
width: 600px;
height: 600px;
text-align: center;
border: 1px solid red;
overflow-y: auto;
}
.list {
text-align: left;
}
.item {
display: inline-block;
width: 200px;
height: 200px;
margin: 10px;
background: gray;
}
</style>
<div class="container">
<div class="list">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
</div>
</body>
如在所附示例中看到的,list
元素未居中。如果删除align: left
样式,则list
元素将居中,但item
元素也将居中(我希望它们向左对齐)
诸如此类的只是给text-align:left;项目并删除text-align:center;从列表
<body>
<style>
.container {
width: 600px;
height: 600px;
text-align: center;
border: 1px solid red;
overflow-y: auto;
}
.item {
display: inline-block;
width: 200px;
height: 200px;
margin: 10px;
background: gray;
text-align: left;
}
</style>
<div class="container">
<div class="list">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>
</div>
</body>
您实际上想实现什么?
现在.container
和.list
的宽度均为600px,因此您看不到列表元素是左对齐还是居中对齐。
首先,.list
和.container
的宽度应不同。然后您的列表应该是一个inline-block
元素,它才能对text-align: center
做出反应。
我为您制作了一个Codepen,以使其更清楚:https://codepen.io/leo-melin/pen/MWYbLLa
.container {
width: 800px;
height: 600px;
text-align: center;
border: 1px solid red;
overflow-y: auto;
}
.list {
display: inline-block;
width: 500px;
border: solid 1px #000; /* Added border to make it visual */
text-align: left;
}
.item {
display: inline-block;
width: 200px;
height: 200px;
margin: 10px;
background: gray;
}
将文本对齐:将CSS属性留给项目类。
<body>
<style>
.container {
width: 600px;
height: 600px;
text-align: center;
border: 1px solid red;
overflow-y: auto;
}
.list {
text-align: center;
}
.item {
display: inline-block;
text-align: left;
width: 200px;
height: 200px;
margin: 10px;
background: gray;
}
</style>
<div class="container">
<div class="list">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>
</div>
</body>