为什么我的 div 不对齐?(CSS网页设计布局)



div 类容器用于包装网页的所有其他项目,我想集中对齐这个容器,但似乎无法弄清楚为什么它不起作用。

编辑:我希望容器本身以视点为中心,然后我想单独对齐它们自己的容器中的项目。

编辑2:我想通了,谢谢大家的回复。我将 HTML 选择器更改为正文,然后将显示更改为 flex,最后将 justify-self 更改为对齐项目。

* {
margin: 0;
padding: 0;
}
html {
display: block;
flex-direction: column;
width: 100%;
justify-self: center;
}
h1 {
text-align: center;
}
.sub {
position: absolute;
}
.container {
width: 50%;
border: 2px black solid;
box-sizing: border-box;
display: inline-flex;
position: relative;
}
<!DOCTYPE html>
<html>
<head>
<link href='style.css' rel='stylesheet'>
<link href="https://fonts.googleapis.com/css?family=Notable|Work+Sans&display=swap" rel="stylesheet">
</head>
<h1 id='main_title'>Website Style Specification - 1</h1>
<body>
<div class='container' id='color_container'>
<h2 class='sub'>Colours</h2>
<div class='color_box' id='color_one'>
<p>Coal</p>
<p>#252525</p>
<p>Background Colour</p>
</div>
<div class='color_box' id='color_two'>
<p>Blood</p>
<p>#ff0000</p>
<p>Text colour</p>
</div>
<div class='color_box' id='color_three'>
<p>Crimson</p>
<p>#af0404</p>
<p>Borders ad foreground colouring</p>
</div>
<div class='color_box' id='color_four'>
<p>Slate</p>
<p>#414141</p>
<p>Element background</p>
</div>
</div>
<div class='container' id='font_container'>
<h2 class='sub'>Fonts</h2>
<div class='font_box' id='font_1'>
<h3>Notable</h3>
<p class='normal'>This is how the text will display on the website.</p>
<p class='italic'>This is how the text will display on the website.</p>
<p class='bold'>This is how the text will display on the website.</p>
</div>
<div class='font_box' id='font_2'>
<h3>WorkSans-Regular</h3>
<p class='normal'>This is how the text will display on the website.</p>
<p class='italic'>This is how the text will display on the website.</p>
<p class='bold'>This is how the text will display on the website.</p>
</div>
</div>
<div class='container' id='text_styles'>
<h2 class='sub'>Text styles</h2>
<div class='text_box' id='text_1'>
<h3 id='sub_headings'>This is a sub heading</h3>
<ul>
<li>HTML: h2</li>
<li>font family: Notable</li>
<li>Font weight: 28px</li>
<li>Text decoration: underline</li>
</ul>
</div>
<div class='text_box' id='text_2'>
<p id='text'>
<ul>
<li>HTML: p</li>
<li>font family: Work sans</li>
<li>font weight: 18px</li>
</ul>
</p>
</div>
</div>
</body>
<footer></footer>
</html>

你在寻找这样的东西吗?

赋予containerdisplay: flexjustify-content: center;的父元素,让弹性框发挥它的魔力。这会将子元素居中放在 X 轴上

* {
margin: 0;
padding: 0;
}
html {
display: block;
flex-direction: column;
width: 100%;
}
body{
width: 100%;
display: flex;
justify-content: center;
color: black;
}
h1 {
text-align: center;
}
.sub {
position: absolute;
}
.container {
width: 50%;
border: 2px black solid;
box-sizing: border-box;
text-align: center;
}
<html>
<body>
<div class="container">
HELLO IM THE CONTAINER
</div>
</body>
</html>

最新更新