Home > Mobile >  Center a div to the right of an image inside a header
Center a div to the right of an image inside a header

Time:05-07

I want a header with an image attached to the left and a div with some text inside, to the right of this image. The div must contain horizontally and vertically centered text.

Something like that: 1

I tried almost everything like relative positioning, float, inline-blocks and columns but I just can't figure out how.

header {
  background-color: rgb(31, 31, 31);
  overflow: hidden;
  padding: 20px 10px;
}

.header-right {
  display: inline-block;
  text-align: center;
}

#imageContainer {
  float: left;
  text-align: center;
  padding: 12px;
}
<header>
  <a id="imageContainer">
    <img id="image" src="test.png">
  </a>
  <div >
    <h1>Centered text here</h1>
  </div>
</header>

EDIT: someone closed the question saying that this answer my question. But i have to center the text in the space between the image container and the very end of the header's width!

CodePudding user response:

The path of least resistance for this particular case is probably just to use flex to keep the element count down. See below.

header {
  display: flex;
  align-items: center;
  background-color: rgb(31, 31, 31);
  padding: 20px 10px;
}

header h1 {
  flex: 1;
  text-align: center;
}
<header>
    <a>
        <img id="image" src="https://picsum.photos/200">
    </a>
    <h1>Centered text here</h1>
</header>

CodePudding user response:

Use display as flex instead of floats

header {
    background-color: rgb(31, 31, 31);
    overflow: hidden;
    padding: 20px 10px;
    display: flex;
}
.header-right {
    text-align: center;
    border: 1px solid white;
    width: 100%;
}
#imageContainer {
    text-align: center;
    padding: 12px;
    border: 1px solid white;
}

#imageContainer:hover, .header-right:hover {
    background-color: white;
    color: black;
}
<header>
    <a id="imageContainer">
        <img id="image" src="test.png">
    </a>
    <div >
        <h1>Centered text here</h1>
    </div>
</header>

  • Related