CSS selector for label without child elements - css

First of all the solution in that question: CSS selector to bold only labels without child elements does not solve my issue.
I have labels with text only and others with text and child input, select and textarea form's elements.
i.e:
<label class="control-label">State
<select name="status" id="status" class="form-control">
<option value="">Choose..</option>
...
</select>
</label>
and other like:
<label for="defect" class="control-label">Error</label>
I need to set white-space: nowrap to labels that has no child HTML elements only and as the above question answers stated, I tried the following:
label{
white-space: nowrap; /* Label without HTML*/
}
label + label {
white-space: normal; /* Label with HTML */
}
However, it does not work.

One solution would be adding a class to the element and using CSS to format it accordingly.
label.empty {
white-space: nowrap;
}
Link to the documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors
The other comment points to using :empty but in your case the <label> contains some text and doesn't apply as empty

AFAIK there is no solution using CSS selectors. The solution proposed by #FabioPontes to control via an additional class name would be the most straight-forward.
Following is a javascript solution that verifies for an element's child nodes and applies a white-space:nowrap if (1) there is only one child node and (2) this node is of type text. Please view node types.
var elements = document.getElementsByClassName("control-label");
for (i = 0; i < elements.length; i++) {
if (elements[i].childNodes.length == 1 && elements[i].childNodes[0].nodeType == 3) {
elements[i].style.whiteSpace = "nowrap";
}
}
<div>
<label class="control-label">State - we need a really long text to check if the white-space nowrap is actually working so lets place this text here.
<select name="status" id="status" class="form-control">
<option value="">Choose..</option>
</select>
</label>
</div>
<div style="margin-top:20px;">
<label for="defect" class="control-label">Error - we need a really long text to check if the white-space nowrap is actually working so lets place this text here.</label>
</div>

The option to add a class has already been suggested by Fabio Pontes and is a good one, but if you don't want to add classes, here are a couple options.
The first thing you could do is modify your markup to wrap each label in a div and then leverage the :only-child pseudo selector. In order for this to work, you'll have to include the select element as a sibling of the label, rather than as a child of it.
.control-label-wrapper label:only-child {
white-space: nowrap;
}
<div class="control-label-wrapper">
<label class="control-label">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut tellus massa. Phasellus dictum mollis lobortis.</label>
<select name="status" id="status" class="form-control">
<option value="">Choose..</option>
</select>
</div>
<div class="control-label-wrapper">
<label for="defect" class="control-label">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut tellus massa. Phasellus dictum mollis lobortis.</label>
</div>
Another option which may not require modifying your makup at all is to use an attribute selector. Perhaps you're already using an attribute for all these childless labels. The example HTML in your question suggests you may be.
label[for="defect"] {
white-space: nowrap;
}
<label class="control-label">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut tellus massa. Phasellus dictum mollis lobortis.
<select name="status" id="status" class="form-control">
<option value="">Choose..</option>
</select>
</label>
<label for="defect" class="control-label">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ut tellus massa. Phasellus dictum mollis lobortis.</label>

Related

Selects all <p> elements if <p> Tag Contains Start with "Read:" Using CSS? [duplicate]

This question already has answers here:
Is there a CSS selector for elements containing certain text?
(20 answers)
Closed 1 year ago.
I have a lot of <p> tags on thousands of pages.
There are hundreds of <p> tags like below.
<p>Read: Example</p>
Those start with Read:.
I want t to apply some CSS to <p> tag only if the paragraph starts with Read:. Is it possible?
This is not posible with CSS alone, you would need Javascript to achieve this.
This example shows you...
#1. How to use Javascript to search your documents p tags and find strings where the 1st index of the string is set to the target string Read: using indexOf().
#2. How to then set an attribute, el.setAttribute(), on that tag that identifies that element as a Read: element containing the string we want to affect in our CSS.
#3. How to use CSS + elements attribute to then style the target elements in the DOM as you want them styled.
const p = [...document.getElementsByTagName('p')] -> create an
array of elements we can then loop over using tag.forEach()
tag.textContent.indexOf("Read:") === 0-> lets find elements that
have target string at the very beginning of the tag.textContent.
tag.setAttribute("data-read", true) -> set the tags data-read
attribute to true
p[data-read="true"] in CSS we style all elements that are p tags
and have the attribute <p data-read="true">
Using this method we are able to use CSS to style the tags and JS to find them.
const p = [...document.getElementsByTagName('p')]
p.forEach(tag=>tag.textContent.indexOf("Read:") === 0 ? tag.setAttribute("data-read", true) : false)
p[data-read="true"] {
background-color: lightgreen;
font-weight: bold;
color: darkgreen;
}
p[data-read="true"]:after {
content: ' *';
}
p[data-read="true"]:before {
content: '* ';
}
<div>
<p>Read: some info</p>
<p>Read: some info</p>
<p>p tag content</p>
<p>more ptag info</p>
<p>Perhaps the p content has a sentence that starts with the string and we do not want to get that one. Read: Speak: Listen:</p>
<p>Read: At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.</p>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p>Read: More</p>
<p>Read: More</p>
<p>Hey</p>
<p>Hello</p>
<p>Lorem ipsum dolor sit amet, consectet Read: More</p>
<script>
let list = document.getElementsByTagName("p");
for (let i = 0; i < list.length; i++) {
if (list[i].textContent.startsWith("Read:")) {
list[i].style.color = "red";
}
}
</script>
</body>
</html>
I don't know if CSS have such selectors but you can still achieve your goal with JavaScript
let list = document.getElementsByTagName("p");
for (let i = 0; i < list.length; i++) {
if (list[i].textContent.startsWith("Read:")) {
list[i].style.color = "red";
}
}

Specifying alternate background image using ngStyle

I am trying to specify an alternate background image for a DIV like so:
<div [ngStyle]="{'background-image':'url(1.jpg), url(2.jpg)'}"></div>
Neither of the images are displaying (it works if I don't specify an alternate image).
Is it possible to specify multiple background images using ngStyle?
Working demo
Template file
<div [ngStyle]='styles'>
<h1>Lorem Ipsum Dolor</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</div>
Ts file
export class AppComponent {
name = 'Angular';
img1 = 'https://www.w3schools.com/css/img_flwr.gif';
img2 = 'https://www.w3schools.com/css/paper.gif'
isSelected: boolean = true;
styles = {};
setCurrentStyles() {
this.styles = {
backgroundImage: this.isSelected ?
`url(${this.img1})`:`url(${this.img2})`
};
}
toogleImage() {
this.isSelected = !this.isSelected;
this.setCurrentStyles();
}
}
Try like this
template.html
<div class="image" [ngStyle]="{background: !isActive ? 'url(https://www.fonewalls.com/wp-content/uploads/Aqua-Solid-Color-Background-Wallpaper-for-Mobile-Phone.png)' : 'url(https://www.fonewalls.com/wp-content/uploads/Midnight-Blue-Solid-Color-Background-Wallpaper-for-Mobile-Phone.png)'}"></div>
cmponent.ts
isActive: boolean = true;
You can also keep your HTML clean with moving all the logic into the component.ts.
In the end you would have something like this:
<div class="image" [ngStyle]="{
'background-image': 'url(' + backgroundImageString + ')'
}"></div>
Then in your component:
private defineBackImage(someArg) {
if (stuff) {
this.backgroundImageString = url1;
} else {
this.backgroundImageString = url2;
}
}
You can trigger this function on init of according to specific events, also you can extend this logic to display much more than 2 backgrounds

Does deep nesting flexbox layout cause performance issue?

I have been working on a ReactJS project where I create most of the components using flexbox layout. Since with react, we can have deeply nested components, so my layout is having nested flexbox layout.
Now my question is, does this have any issue with performance? On a single page, there are many components and each component have 3 to 4 level nested flexbox layout. Will that cause a performance issue?
Have done a little test. Rendered 100 components, each with 10 nested layout. With and without flexbox. Here are the code snippets:
Component/index.js
#CSSModules(styles, { allowMultiple: true })
export default class TheComponent extends Component {
render() {
const { deepNest, flex } = this.props
return (
<div>{ this.renderComp(deepNest, flex) }</div>
)
}
renderComp(deepNest, flex) {
const flexProperties = [
{ justifyContent: "center", alignItems: "center" },
{ justifyContent: "flex-start", alignItems: "flex-end" },
{ flexDirection: "row" }
]
const content = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum quis ligula vel elementum. Integer non rhoncus purus, eget dignissim ante.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum quis ligula vel elementum. Integer non rhoncus purus, eget dignissim ante. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum quis ligula vel elementum. Integer non rhoncus purus, eget dignissim ante."
]
if (deepNest > 0 && flex) {
return (
<div styleName="containerFlex" style={flexProperties[deepNest % 3]}>
<div styleName="contentFlex" style={flexProperties[deepNest % 3]}>
{ content[deepNest % 3] }
</div>
<div styleName="nestedFlex" style={flexProperties[deepNest % 3]}>
{ this.renderComp(deepNest - 1, flex) }
</div>
</div>
)
}
if (deepNest > 0 && !flex) {
return (
<div styleName="container">
<div styleName="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus interdum quis ligula vel elementum. Integer non rhoncus purus, eget dignissim ante.
</div>
<div styleName="nested">
{ this.renderComp(deepNest - 1, flex) }
</div>
</div>
)
}
}
}
WithFlex/index.js
import TheComponent from "../Component"
#CSSModules(styles, { allowMultiple: true })
export default class WithFlex extends Component {
constructor(props) {
super(props)
this.state = { render: false }
}
render() {
const {render} = this.state
// number of components to render
const arr = _.range(100)
return (
<div>
<div
style={{ display: "block", padding: 30, lineHeight: "60px" }}
onClick={() => this.setState({render: !render})}>
Start Render
</div>
{ render && arr.map((i) => <TheComponent key={i} deepNest={10} flex={true}/> ) }
</div>
)
}
}
WithoutFlex/index.js
import TheComponent from "../Component"
#CSSModules(styles, { allowMultiple: true })
export default class WithoutFlex extends Component {
constructor(props) {
super(props)
this.state = { render: false }
}
render() {
const {render} = this.state
// number of components to renders
const arr = _.range(100)
return (
<div>
<div
style={{ display: "block", padding: 30, lineHeight: "60px" }}
onClick={() => this.setState({render: !render})}>
Start Render
</div>
{ render && arr.map((i) => <TheComponent key={i} deepNest={10} flex={false}/> ) }
</div>
)
}
}
Results from Chrome dev-tool timeline.
WithFlex
WithoutFlex
Summary
The difference is not that much. Also in flexbox, I put random properties to choose from. So I think it's alright with the performance. Hope it will help other devs.
Old flexbox (display: box) is 2.3x slower than new flexbox (display: flex).
Regular block layout (non-float), will usually be as fast or faster than new flexbox since it’s always single-pass. But new flexbox should be faster than using tables or writing custom JS-base layout code.
For more info
Article1
Article2

Can't get style sheet to work

I am trying to create my first webapp using google apps script. I am trying to follow the examples but it is not working. I created a stylesheet.html tab along with my main html page. But none of my formatting is working. I thought google appended the files together. FYI, my styles work fine if I include them at the bottom of the main page.
This is my code.gs page:
function doGet() {
return HtmlService.createHtmlOutputFromFile('frontpage')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
This is my main page called frontpage.html :
<!DOCTYPE html>
<html lang="en">
<?!= HtmlService.createHtmlOutputFromFile('stylesheet').getContent(); ?>
<!-- google scripts says to not include header & body tags ?? -->
<meta charset="utf-8">
<title>Borah Physics</title> <!-- google syas not to use title tag need another way to set title.-->
<h1><div style="text-align:center">Physics Homework</div></h1>
<!--List of available assignments. This needs to be updated as assignments are added.
Add assignment name and the ssID of the spreadsheet containing the questions.
when clicked need to return value (ssid) as sheetID.-->
<select id="assignment">
<option sheetID="1ajedscAjuXDsUOcQRzru5-bhUIluGn3fPPsoN-Ww5wU">Kinematics 1</option>
<option sheetID="10mCGpLRwv8ETFbW3RwisI45s_x3-ZItatzq_vU0wacs">Dynamics</option>
</select>
<!--Question should be string variable activeQuestion It will get updated when the question number changes.-->
<div id="question">
<br>
<br>
Question Here
<br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
<br> <br>
</div>
<!-- If question has an image it will go here.-->
<div id="qImage">
Along with image (if needed)
<br>
</div>
<!-- This is the user inputed answer. It needs to be recorded in the response sheet of the spreadsheet and
compared to the correct answer. (in the comparison we need to add a within x% variable so if the answer
is close it is counted as correct. This accounts for thinks like g=10 m/s^2 vs 9.8 m/s^2.-->
<div id="answer">
<label>Answer:</label>
<input type="text" name="answer"/>
<input type="Submit" value="Submit"/>
<br>
<br>
</div>
<!-- bottom navigation list-->
<ul id="nav">
<li><a> </a></li>
<li><input type="button" onclick="previous()" value="Previous"></li> <!-- goes to previous question (calls previous function)-->
<li><a > Correct: 4/12 </a></li> <!-- need to insert variables #correct & total # questions-->
<li><input type="button" onclick="next()" value="Next"></li> <!-- goes to next question (calls next function).-->
<li><a> </a></li>
</ul>
and finally my stylesheet.html page
<style>
#assignment{
width: 20%; margin: 10 ;
position: absolute;
right: 10px;
}
#question {
width: 90%; margin: 0 auto;
}
#qImage{
width: 90%; margin: 0 auto;
}
#answer {
width: 90%; margin: 0 auto;
}
#nav {
text-align: justify;
min-width: 400px;
}
#nav:after {
content: '';
display: inline-block;
width: 100%;
}
#nav li {
display: inline-block;
}
</style>
My output shows the at the top of the page as if it were text. So I am not connecting the style sheet to the frontpage.
I have not even attempted to understand functions or javascript yet. Lots to learn. (This is a physics homework app I hope to get working before school starts!) All help is appreciated. Any tutors out there?
thanks.
Change createHtmlOutputFromFile to createTemplateFromFile in the doGet() function.
Should be:
return HtmlService
.createTemplateFromFile('frontpage')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
If a file has a scriptlet in it, it's a template. Your frontpage file has a scriptlet in it. The scriptlet is:
<?!= HtmlService.createHtmlOutputFromFile('stylesheet').getContent(); ?>
You can also call a server function from a scriptlet instead of using HtmlService directly inside the scriptlet.

Repeating loop using for condition

<li style="width: 20%">
<div class="thumbnail" style="width: 200px">
<div class="fader">
<img src="./Images/slide-01.jpg" alt="">
</div>
<div class="caption">
<h5>
Thumbnail label</h5>
<p>
porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.</p>
<p>
<p align="center">
<asp:Button runat="server" class="btn btn-primary" ID="lnk" Text="View" />
</p>
</div>
</div>
</li>
If i want to repeat list 12 times using for loop or some other looping condition.
Can you help how to solve !!
You can use a asp:repeater for this type of scenario if using webforms
using a repeater
Bind repeater to generic list
Since you're using ASP.NET and you want to display server-side controls (asp:Button) you can't simple construct your HTML as string and output it to the page.
Define your UL/OL tag with runat = "server" attribute, so it is accessible in server-side code.
<ul id="myList" runat="server" ></ul>
Then add LI and the rest of them as child Controls of the original element.
Dim li As HtmlGenericControl
For I = 1 To 12
li = New HtmlGenericControl("li")
li.Style("width") = "width: 20%"
myList.Controls.Add(li)
Next
The VB.NET example above builds UL with 12 LI elements. Similarly an LI element has .Controls property of it's own to which you can add other controls (DIV etc.)

Resources