【问题标题】:Centering and floating within the same container在同一个容器内居中和浮动
【发布时间】:2015-10-25 07:55:38
【问题描述】:

我有一个容器,其中有一些内容居中,但我想在左边放一些东西,但我不知道如何做到这一点。

这是使用absolute 定位的唯一方法吗?这是我一直在使用的代码来展示广告的示例:

HTML:

<div class="container">
  <p class="one">Left</p>
  <p style="clear: both;"></p>
  <div class="center">Center</div>
</div>

CSS:

.container {
  background-color: gray;
  text-align: center;
}

.container .one {
  float: left;
  background-color: aqua;
}

.clearfix:after,
.clearfix:before
{
  display: table;
  content: " ";
  clear: both;
}

.container .center {
  display: inline-block;
  background-color: green;
}

代码笔:

http://codepen.io/anon/pen/NqeBNp

【问题讨论】:

  • 嗯,是的,我想是的。我想我在第一个元素之后尝试清除浮动,我忘记了我真的不需要,并且可以在容器上应用一个 clearfix 来处理它。
  • @Vitorinofernandes 刚刚对此进行了更多测试,但实际上并没有按我的意愿工作;例如,如果文本在左侧很长,您会注意到居中的文本将在剩余的可用空间内居中,而不是在容器的整个宽度内居中。

标签: html css css-float css-position centering


【解决方案1】:

尝试将display:inline-blockfloat:left 与两个div 的一些width 一起应用。

.container {
  background-color: gray;
  text-align: center;
  overflow: auto;
}
.container .one {
  display: inline-block;
  float: left;
  width: 33%;
  background-color: aqua;
}
.container .center {
  display: inline-block;
  float: left;
  width: 33%;
  background-color: green;
}
<div class="container">
  <div class="one">Left</div>
  <div class="center">Center</div>
</div>

【讨论】:

  • 谢谢,但我并不想限制元素的宽度。
【解决方案2】:

你应该使用 Flexbox,它非常好用。让我知道这是否是您要找的?

截图:

代码的实时实例 --> https://jsfiddle.net/7fo5ceb6/

//HTML

<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet">    
</head>
<body>
<div id="container">
    <div>left</div>
    <div>center</div>
    <div>right</div>
</div>
</body>
</html>

//CSS

body{
    margin: 0 !important;
    height: 100vh;
    width: 100vw;
}

#container{
    display: -webkit-flex;
    display: flex;

    height: 60px;
    width: 100%;

    background: #5c5c5c;
}
#container>div{
    padding: 10px 0px;
    text-align: center;

    -webkit-flex: 1;
    flex: 1;

    -webkit-align-self: center;
    align-self: center;

    margin: 5px;
    background: #ccc;
}

【讨论】:

  • 唯一的问题是IE9 不支持它,IE10 只支持 2012 版本,不管这意味着什么。
  • @Brett 我最近在 IE 上进行了兼容性测试,上面的代码可以正常工作,但是 IE 仍然没有内置支持“align-items”,即使在 IE 11 smh 中也无法正常显示...
  • 嗯好的。那么你用哪个 IE 版本测试了上述内容?
  • @Brett 对不起,您对 IE9 的看法是正确的,但 IE10 工作正常,除了“align-items”和“flex-wrap”等等......真是个可怕的浏览器,不是吗?
  • 肯定是哈哈……不支持IE8也可以,可惜还是要支持IE9
猜你喜欢
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 2014-10-31
  • 2013-09-17
  • 2018-01-31
  • 2023-03-21
相关资源
最近更新 更多