I have a positioned Text element that sits on top of an Image element in a Stack. I'd like to apply a simple background color to that Text element, so that it frames the text like a caption box:
I can do this by inserting a Container as another positioned child in that Stack. But I'd have to recalculate the width every time the text string changes, which is sub-optimal. Is there a better way?
var stack = new Stack(
children: <Widget>[
new Image.asset ( // background photo
"assets/texture.jpg",
fit: ImageFit.cover,
height: 600.0,
),
new Positioned ( // headline
child: new Container(
decoration: new BoxDecoration (
backgroundColor: Colors.black
),
),
left: 0.0,
bottom: 108.0,
width: 490.0,
height: 80.0,
),
new Positioned (
child: new Text (
"Lorem ipsum dolor.",
style: new TextStyle(
color: Colors.blue[500],
fontSize: 42.0,
fontWeight: FontWeight.w900
)
),
left: 16.0,
bottom: 128.0,
)
]
);
Put the text in an inline element, such as a <span> . And then apply the background color on the inline element. An inline element is as big as its contents is, so that should do it for you.
You can change the background color of text in HTML by adding a background-color property to a paragraph (p) or heading (H1, H2, H3... ) element. Add this property either via inline CSS or on your website's CSS code.
Changing Text Background Color in CSS. To change the background color of the inline text, go to the <head> section. Simply add the appropriate CSS selector and define the color and background-color property with the values you want.
Select Start > Settings > Personalization > Colors, and then choose your own color, or let Windows pull an accent color from your background.
Just nest the Text element as a child within the Container that has the BoxDecoration (i.e. background color); the Container will stretch to fit the Text inside. Additionally, one can specify padding for that Container, which eliminates the need to hardcode a width/height for the box.
var stack = new Stack(
children: <Widget>[
new Image.asset ( // background photo
"assets/texture.jpg",
fit: ImageFit.cover,
height: 600.0,
),
new Positioned ( // headline
child: new Container(
child: new Text (
"Lorem ipsum dolor.",
style: new TextStyle(
color: Colors.blue[500],
fontSize: 42.0,
fontWeight: FontWeight.w900
)
),
decoration: new BoxDecoration (
backgroundColor: Colors.black
),
padding: new EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),
),
left: 0.0,
bottom: 108.0,
),
]
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With