简体   繁体   English

元素左侧和元素右侧的CSS样式填充空间

[英]CSS Styling fill space left in the left of the element and the right of the element

imagine an element, which is centered in its container, has its width, but don't know the exact width, something like text and i want the left space and right space to be same and colored, something like this: 想象一个位于其容器中心的元素具有其宽度,但不知道确切的宽度,例如文本,我希望左侧空间和右侧空间相同且着色,如下所示:

----------------- Test This ----------------- -----------------测试此-----------------

 #left { background-color: red; } #middle { width: 200px; /* it might be different */ } #right { background-color: red; } 
 <div id="left"></div> <div id="middle"></div> <div id="right"></div> 

Can be achieved using display: flex 可以使用display: flex实现

 .wrapper { display: flex; text-align: center; } #left { flex: 1; background-color: red; } #middle { /* it might be different */ } #right { flex: 1; background-color: red; } 
 <div class="wrapper"> <div id="left"></div> <div id="middle">Some text</div> <div id="right"></div> </div> <br/> <div class="wrapper"> <div id="left"></div> <div id="middle">Some long text can go here!</div> <div id="right"></div> </div> 

    .container{
       display:flex;
    }
     .main-body{
       flex:1 1 auto;
    }
    #left{
        background-color: red;
   }
   #middle{
        width: 200px;
       text-align:center;
  }
    #right{
        background-color: red;
    }
  <div class="container">
    <div class="main-body" id="left"></div>
    <div id="middle">Hello</div>
    <div  class="main-body" id="right"></div>
  </div>

Split into equal spaces using bootstrap and then fill color 使用引导程序分成相等的空间,然后填充颜色

<div class="container">
<div class="col-md-12 col-sm-12 col-xs-12">
    <div class="row">
        <div class="col-md-4 col-sm-4 col-xs-4 fill-color"> h</div>
        <div class="col-md-4 col-sm-4 col-xs-4">h</div>
        <div class="col-md-4 col-sm-4 col-xs-4 fill-color">h</div>
    </div>
</div>

.fill-color {
   background: red;
}

Working fiddle 工作提琴

Surround your div by another div "container" , now you don't need left and right divs.. Your Text here, Div is surrounded by container div #container { background-color: red; 用另一个div“容器”包围div,现在您不需要左右div。在这里,Div被容器div所包围。div #container {background-color:red; } }

    #middle {
        font-size: 30px;
        width: 80%;
        margin: auto;
        text-align: center;
        background-color: white;
    }


</style>

您可以在页面的左右div上添加margin属性。固定左右div的宽度。尝试一下,我想它将解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM