I’m trying to make a segment of a webpage where an image will appear on the left or right and directly next to it there can be text centered on its segment of the page (see image).
However, the element holding the text is wider than the available space for it because its defaulting to the width of the entire page despite being slightly to the right, causing the text to be off-center.
Is there a way to account for the variable width of the image without this overflow?
Here are the HTML and CSS snippets for the elements I’m using and a photo of the issue:
HTML
<div class="row" style="max-height: 80%">
<img src="./images/garden-state.webp">
<div class="column" style="width:min-content;">
<div class="title" style="background-color: #1b1b1b; max-height: 30%;"><h3>Garden State</h3></div>
</div>
</div>
CSS
.row {
display: flex;
flex:0 0 100%;
max-height:80%;
width:100%;
}
.column {
display: flex;
flex-direction: column;
flex:0 0 100%;
justify-items: center;
max-height:50%;
width:100%;
}
img {
display:flex;
margin: 0;
padding: 0;
object-fit: contain;
}
Ideally the text should be horizontally centered in the visible portion of the header element. I’ve tried multiple different values for the width
variable, from different percentages to min-content
and the such with nothing changing at all.
Any help is appreciated!
3
Answers
If you are just looking to center the text in h3. You can just add
h3 {text-align: center}
. It should center the text to available width.However, if you want to remove the extra bit of unnecessary horizontal scroll.
You can try something like this, where you remove the set width and hide the overflow so the width will be set automatically. You can take a look at this for example. Codepen_Example
The horizontal scrolling is because you changed
flex-shrink
to "0" via the shorthand declarationflex:0 0 100%;
, preventing the container from shrinking to fit the available space. Theflex
declaration is not even needed.CSS Code
HTML Code
Try out this code…
Upvote if this was helpful 🙂