Matteo
Matteo

Reputation: 79

Moving 2 elements apart within a div

There is a h1 and clickable image within the div called #search-bar (unfortunately I don't know where to add the relevant image.. apologies) I would like to move them apart as I did. I was wondering if there is any simplier and nittier solution in order to shorten the CSS code.Thank you.

#search-bar {
    background: #C75000;
    margin: 20px 90px 20px 75px;
    padding: 1rem;
    color:white;

}

#search-bar a, h1{
    display:inline-block;
    /* transform: translateX(50%); */
    border: 5px solid black;
    position: relative;
    left: 200px;
}   

#search-bar h1{
    left:50px;
}

#search-bar a{
    left:400px;
}
<div id="search-bar">
            <h1>Can I use?</h1>  
            <a href="https://www.amazon.com/">
                <img alt="cog" src="cog-trans.png" width="30" height="30">
             </a>
        </div>

Upvotes: 0

Views: 692

Answers (2)

StepUp
StepUp

Reputation: 38104

You can use justify-content: space-between if you want to have space between items:

As mdn says:

The CSS justify-content property defines how the browser distributes space between and around content items along the main-axis of a flex container, and the inline axis of a grid container.

In addition, there are more values for justify-content such as space-around, flex-start, and flex-end and so on. Read more about properties.

An example:

#search-bar {
  background: #C75000;
  margin: 20px 90px 20px 75px;
  padding: 1rem;
  color:white;
  display: flex;
  justify-content: space-between;
}

#search-bar a, h1{      
  border: 5px solid black;    
}
  <div id="search-bar">
    <h1>Can I use?</h1>
    <a href="https://www.amazon.com/">
        <img alt="cog" src="cog-trans.png" width="30" height="30">
     </a>
</div>

Upvotes: 1

Morta1
Morta1

Reputation: 619

Using flexbox to style (example)

    #search-bar {
      display: flex;
      justify-content: space-around;
      align-items: center;
      background: #c75000;
      margin: 20px 90px 20px 75px;
      padding: 1rem;
      color: white;
    }

Upvotes: 1

Related Questions