Home > front end >  Positioning a textbox beside an image using HTML and CSS?
Positioning a textbox beside an image using HTML and CSS?

Time:03-17

I'm currently working on creating a simple textbox next to a positioned image using HTML and CSS. I am currently doing this by using a blue image sized to the same dimensions and then placing my text on top of it.

This is the current setup, its the image, followed by the blue box image with text placed on top:

You can view the image here

My HTML and CSS currently looks like this:

<html>
<style>

p {
  margin-right: 80px;
  margin-left: 80px;
  font-size: 1.3vw;
  font-family: Arial;
}

h4 {
  margin-right: 80px;
  margin-left: 80px;
  font-size: 1.4vw;
  font-family: Arial;
  font-weight: bold;
}

.bottom_container {
  position: relative;
  text-align: center;
  color: white;
}

.right-textbox {
  position: absolute;
  color: white;
  top: 0%;
  left: 50%;
  width: 40%;
}

.bottom__img {
  width: 40%;
}
</style>
    <div >
        <img  src="https://imgur.com/n8gXRcX.jpg" alt="PA State Capital Building" >
        <img  src="https://imgur.com/xUIkixp.jpg" alt="" >
        <div >
            <h4>The Pennsylvania State Capital</h4>
            <p>Text goes here</p>
        </div>
    </div>

</html>

Could I use the background color for the textbox and somehow scale it to fit the same height and width of the main image instead of having to match it with a separate image of the same dimensions?

CodePudding user response:

Here is a solution with CSS grid:

img{
  max-width: 100%;
}
.bottom_container{
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.5em;
}
.right-textbox{
  background: blue;
  color: white;
  text-align: center;
}
<div >
  <img  src="https://imgur.com/n8gXRcX.jpg" alt="PA State Capital Building">
  <div >
    <h4>The Pennsylvania State Capital</h4>
    <p>Text goes here</p>
  </div>
</div>

or a flexible height approach:

img{
  max-width: 100%;
}
.bottom_container{
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 0.5em;
}
.image-container{
  background-image: url("https://imgur.com/n8gXRcX.jpg");
  background-size: cover;
}
.right-textbox{
  background: blue;
  color: white;
  text-align: center;
}
<div >
  <div ></div>
  <div >
    <h4>The Pennsylvania State Capital</h4>
    <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
  </div>
</div>

Learn more about CSS Grid

  • Related