html - 居中 <div>

标签 html css center fixed

晚上好

我正在尝试将“联系方式”div 居中。我使用了下面的代码,但是在使用 position: fixed 之后它看起来不像是居中的。在使用 position:fixed 时,是否有另一种方法可以使其完美居中?我想在上下滚动时保持 div 居中。任何帮助将不胜感激,谢谢!

.secondary {
	height: 350px;
	width: 400px;
	background-color: #ccc;
	box-shadow: 5px 5px 5px #000;
	margin-top: 200px;
	position: fixed;
	margin-left: 40%;
}
<section class="secondary">
	<h3>Contact Details</h3>
	  <ul class="contact-info">
	    <li class="phone"><a href="tel:###-###-####">###-###-####</a></li>
		<li class="mail"><a href="mailto:e************@gmail.com"             target="_blank">e************@gmail.com</a></li>
		<li class="twitter"><a href="http://twitter.com/intent/tweet?screen_name=ec#######" target="_blank">@ec*******</a></li>
		<li class="linkedin"><a href="http://linkedin.com/in/e####-######-8a791988" target="_blank">Edwin Castro</a></li>
	</ul>
</section>

最佳答案

由于您为 div 使用固定尺寸而不是使其具有响应性,因此您可以使用:

.secondary {
    height: 350px;
    width: 400px;
    background-color: #ccc;
    box-shadow: 5px 5px 5px #000;
    position: fixed;
    margin-left: -200px;
    margin-top: -175px;
    left: 50%;
    top: 50%;
}

它所做的只是将元素移动到中心,然后使用负边距将其拉回其总宽度/高度的一半,使其完美居中。

虽然这感觉像是一种过时的方法。如果您确实希望使其具有响应性,您可以尝试类似的方法:

.secondary {
    height: 350px;
    width: 100%;
    max-width: 400px;
    background-color: #ccc;
    box-shadow: 5px 5px 5px #000;
    position: fixed;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

它可能不会为您提供您正在寻找的精确样式,但它会让您走上正确的道路。

关于html - 居中 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41798415/

相关文章:

javascript - 如何删除 "previous"和 "next"innerHTML 而不破坏它们

html - 浏览器无法正常调整图像大小

html - 如何让用户查看已发布的具有 css 样式的 IIS 页面?

java - 如何设置合适的布局

php - 在输入表单上居中文本

html - 使用 CSS 绘制矩形

html - 动画 CSS 列和 SVG

javascript - onMouseOver 重复改变图片的背景颜色

javascript - 在另一个 div 旁边显示相对位置的 div

html - 2个绝对定位的div,一个挡住另一个