我有一个元素,我希望它相对于页面居中,同时有一个 float 元素与其内联。
HTML:
<div class="container">
<span class="centerMe">I should be centered</span>
<span class="ontheright">I'm on the right!</span>
</div>
CSS:
.container{ text-align:center }
.centerMe{
margin-left:auto;
margin-right:auto;
}
.ontheright{float:right;}
问题是居中元素相对于剩余空间居中,在 float 元素用完它之后。我希望它相对于容器的整个宽度居中。我试过使用 position:absolute
而不是 float,但是当屏幕太小时它会发生碰撞。
最佳答案
您还可以将相对定位设置为 center-me div,以便您可以定义一个 left 属性:
.centerMe {
margin-left:auto;
margin-right:auto;
position: relative;
left: 70px;
}
对于在小屏幕宽度上发生碰撞的问题,您可以使用媒体查询:
@media screen and (max-width: 320px) {
.ontheright {
float: none;
top: 20px;
}
}
请务必在您的 HTML 中包含媒体查询的元视口(viewport)标记。
这是一个fiddle
关于html - 当 float 元素旁边有元素时,如何使元素居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18114172/