html - 我想让一个 div 在另一个 div 中居中,另一个 div 在它下面居中。

标签 html css positioning

这是我的 CSS 和 html:

.container {
	background-image: url('./images/bg.jpg');
	height: 500px;
	width: 960px;
	margin: auto;
}

.logo {
	margin: auto;
	text-align: center;
	width: 960px;
	height: 100px;
	position: relative;
	top: 200px;
}

ul {
	list-style: none;
}

li {
	display: inline;
}

.nav {
	margin: auto;
	text-align: center;
	padding-right: 35px;
	clear: both;
}
<div class="container">
	<div class="logo">
		<h1>My Page</h1>
	</div>
	
	<div class="nav">
		<ul>
			<li><a href="#">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Contact</a></li>
		</ul>
	</div>

我认为它们与我定位 <div class="logo"></div> 的方式不同可能是正确的,但我不确定如何将内容放在 div 中,我发现的任何解决方案似乎都会影响 <div class="nav"></div> 的定位.

所以这个问题有两个方面 - 我如何定位 <div class="logo"></div>集中在 <div class="container"></div> 内然后如何放置 <div class="nav"></div>下面<div class="logo"></div>

感谢您的帮助。

最佳答案

你可以使用 flexbox 来做到这一点。
https://jsfiddle.net/bjdvz1km/

.container {
	background-image: url('./images/bg.jpg');
	height: 500px;
	width: 960px;
  text-align: center;
  margin: auto;
  
  display: flex;
  flex-wrap: wrap;
  align-content: center;
}

.logo {
	margin: auto;
	width: 960px;
	height: 100px;
}

ul {
	list-style: none;
}

li {
	display: inline;
}

.nav {
	margin: auto;
	padding-right: 35px;
	clear: both;
}

body {
  margin: 0;
}
<div class="container">
  
  <div class="logo">
    <h1>My Page</h1>
  </div>
  
  <div class="nav">
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </div>

</div>

关于html - 我想让一个 div 在另一个 div 中居中,另一个 div 在它下面居中。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41386623/

相关文章:

html - 使用百分比的绝对定位会产生意想不到的结果

css - 定位问题

html - 使用显示 :table have 100% height of parent div 制作 div

javascript - css 样式不工作和 js

javascript - 如何使用 Cypress 检测 HTML 表单验证中 setCustomValidity 的输出

css - 在浏览器加载时解析 CSS 文件

javascript - 滚动然后捕捉到顶部

javascript - 使用 setAttribute 方法() 的 Aurelia 自定义属性

html - CSS 未应用于溢出

html - 我的容器周围有白色边界线